internal/codescan/python_test.go

177 lines · 7074 bytes

6 symbols in this file
  1package codescan
  2
  3import (
  4	"errors"
  5	"testing"
  6
  7	"gitbay.org/gitbay/internal/store"
  8)
  9
 10func TestJoinedOutsideLists(t *testing.T) {
 11	for _, tc := range []struct {
 12		name, src string
 13		line      int
 14		want      bool
 15	}{
 16		{"call in a comprehension", "rows = [\n    r[\"a\"]\n    for r in conn.execute(\n        \"select a \"\n        \"from t\",\n        (x,),\n    )\n]\n", 4, true},
 17		{"call in a list", "rules = [\n    Rule(\n        \"name\",\n        \"one message \"\n        \"over two lines\",\n    ),\n]\n", 4, true},
 18		{"tuple in a list", "[(\"a\" \"b\", 1)]\n", 1, true},
 19		{"list element", "names = [\n    \"alpha\"\n    \"beta\",\n]\n", 2, false},
 20		{"set element", "{\"a\" \"b\", \"c\"}\n", 1, false},
 21		{"one-element list", "raise Failed([\n    \"a message \"\n    \"over two lines\"\n])\n", 2, false},
 22		{"list and call on one line", "[\"a\" \"b\", f(\"c\" \"d\")]\n", 1, false},
 23		{"f-string with nested quotes", "[f(f\"{x[\"k\"]}\" \"y\")]\n", 1, true},
 24		{"triple-quoted", "[g(\"\"\"a\nb\"\"\" \"c\")]\n", 1, true},
 25		{"comment between", "[g(\"a\"  # note ]\n  \"b\")]\n", 1, true},
 26		{"no join on the line", "[g(\"a\")]\n", 1, false},
 27	} {
 28		lines, ok := joinedOutsideLists([]byte(tc.src))
 29		if !ok {
 30			t.Errorf("%s: not read", tc.name)
 31			continue
 32		}
 33		if lines[tc.line] != tc.want {
 34			t.Errorf("%s: line %d outside = %v, want %v (%v)", tc.name, tc.line, lines[tc.line], tc.want, lines)
 35		}
 36	}
 37	for _, src := range []string{`x = ["a`, `x = ("a" "b"`, "x = '''a", `x = f"{y"`, `x = )`} {
 38		if _, ok := joinedOutsideLists([]byte(src)); ok {
 39			t.Errorf("%q read", src)
 40		}
 41	}
 42}
 43
 44func TestScopeChecksJoinedStrings(t *testing.T) {
 45	rule := "opt.opengrep-rules.python.lang.correctness.common-mistakes.string-concat-in-list"
 46	files := map[string]string{
 47		"call.py":   "x = [\n    f(\n        \"a \"\n        \"b\"\n    )\n]\n",
 48		"list.py":   "x = [\n    \"a\"\n    \"b\",\n]\n",
 49		"broken.py": "x = [f(\"a\" \"b\"\n",
 50	}
 51	read := func(p string) ([]byte, error) {
 52		if src, ok := files[p]; ok {
 53			return []byte(src), nil
 54		}
 55		return nil, errors.New("missing")
 56	}
 57	findings := []store.SecurityFinding{
 58		{Rule: rule, Path: "call.py", Line: 3},
 59		{Rule: rule, Path: "list.py", Line: 2},
 60		{Rule: rule, Path: "call.py", Line: 1},
 61		{Rule: rule, Path: "broken.py", Line: 1},
 62		{Rule: rule, Path: "gone.py", Line: 1},
 63		{Rule: "other", Path: "call.py", Line: 3},
 64	}
 65	kept, aside, _ := Scope{Read: read}.Apply(findings)
 66	if aside.Joined != 1 || len(kept) != 5 {
 67		t.Fatalf("kept %+v aside %+v", kept, aside)
 68	}
 69	for _, f := range kept {
 70		if f.Path == "call.py" && f.Line == 3 && f.Rule == rule {
 71			t.Errorf("joined-in-a-call hit kept")
 72		}
 73	}
 74	if kept, aside, _ := (Scope{}).Apply(findings); aside.Joined != 0 || len(kept) != 6 {
 75		t.Errorf("without Read: kept %d aside %+v", len(kept), aside)
 76	}
 77}
 78
 79func TestReturnLines(t *testing.T) {
 80	src := "TARGETS = {\n" +
 81		"    \"a\": lambda p: f\"x:{p['k']}\",\n" +
 82		"}\n" +
 83		"def f(x):\n" +
 84		"    return (\n" +
 85		"        x\n" +
 86		"    )\n" +
 87		"s = \"return\"  # return\n" +
 88		"returned = 1\n" +
 89		"class A:\n" +
 90		"    def __init__(self):\n" +
 91		"        self.k = sorted(r, key=lambda r: r[0])\n"
 92	lines, ok := returnLines([]byte(src))
 93	if !ok || len(lines) != 1 || !lines[5] {
 94		t.Errorf("lines = %v ok %v", lines, ok)
 95	}
 96	if _, ok := returnLines([]byte("x = 'open\n")); ok {
 97		t.Error("unclosed string read")
 98	}
 99}
100
101func TestPyNames(t *testing.T) {
102	n := pyNames{methods: map[string]bool{}, attrs: map[string]bool{}}
103	n.add([]byte("@dataclass\nclass Actor:\n    is_admin: bool\n    is_owner: bool = False\n" +
104		"    @property\n    def is_active(self):\n        return True\n" +
105		"    @functools.cached_property\n    def is_cached(self):\n        return True\n" +
106		"    def is_method(self):\n        return True\n" +
107		"    async def is_async(self):\n        return True\n"))
108	n.add([]byte("class B:\n    def __init__(self):\n        self.is_set = True\n" +
109		"def f(user):\n    if user.is_used:\n        return user.is_used2\n" +
110		"x.is_compared == 1\n"))
111	for name, want := range map[string]bool{
112		"is_admin": true, "is_owner": true, "is_active": true, "is_cached": true, "is_set": true,
113		"is_method": false, "is_async": false, "is_used": false, "is_used2": false, "is_compared": false, "is_unknown": false,
114	} {
115		if got := n.attribute(name); got != want {
116			t.Errorf("%s: attribute = %v, want %v", name, got, want)
117		}
118	}
119	n.add([]byte("class C:\n    def is_admin(self):\n        return False\n"))
120	if n.attribute("is_admin") {
121		t.Error("is_admin is a method somewhere and still an attribute")
122	}
123}
124
125func TestTestPath(t *testing.T) {
126	for p, want := range map[string]bool{
127		"Tests/OrgCoreTests/CalcTests.swift":      true,
128		"Sources/App/AppTests.swift":              true,
129		"internal/x/x_test.go":                    true,
130		"tests/web/test_views.py":                 true,
131		"pkg/test_util.py":                        true,
132		"src/__tests__/a.js":                      true,
133		"web/src/api.test.ts":                     true,
134		"conftest.py":                             true,
135		"Sources/CityAppKit/Audio/AudioMix.swift": false,
136		"src/latest.py":                           false,
137		"contest/main.go":                         false,
138	} {
139		if got := testPath(p); got != want {
140			t.Errorf("%s: test = %v, want %v", p, got, want)
141		}
142	}
143}
144
145func TestScopeChecksPythonNamesReturnsAndTests(t *testing.T) {
146	files := map[string]string{
147		"app/users.py":   "@dataclass\nclass Actor:\n    is_admin: bool\n    def is_live(self):\n        return True\n",
148		"app/records.py": "T = {\n    \"a\": lambda p: p,\n}\ndef f():\n    return 1\n",
149		"vendor/x.py":    "def is_admin(self):\n    pass\n",
150	}
151	read := func(p string) ([]byte, error) {
152		if src, ok := files[p]; ok {
153			return []byte(src), nil
154		}
155		return nil, errors.New("missing")
156	}
157	attr := "opt.opengrep-rules.python.lang.maintainability.is-function-without-parentheses"
158	ret := "opt.opengrep-rules.python.lang.maintainability.return-not-in-function"
159	rnd := "opt.opengrep-rules.swift.lang.crypto.insecure-random"
160	findings := []store.SecurityFinding{
161		{Rule: attr, Path: "app/views.py", Line: 3, Message: `Is "is_admin" a function or an attribute? …`},
162		{Rule: attr, Path: "app/views.py", Line: 4, Message: `Is "is_live" a function or an attribute? …`},
163		{Rule: attr, Path: "app/views.py", Line: 5, Message: `Is "is_dir" a function or an attribute? …`},
164		{Rule: ret, Path: "app/records.py", Line: 2},
165		{Rule: ret, Path: "app/records.py", Line: 5},
166		{Rule: rnd, Path: "Tests/CoreTests/CalcTests.swift", Line: 1},
167		{Rule: rnd, Path: "Sources/Audio/Mix.swift", Line: 1},
168	}
169	paths := []string{"app/users.py", "app/records.py", "vendor/x.py", "README.md"}
170	kept, aside, _ := Scope{Read: read, Paths: paths}.Apply(findings)
171	if aside.Attributes != 1 || aside.NoReturn != 1 || aside.InTests != 1 || len(kept) != 4 {
172		t.Fatalf("kept %+v aside %+v", kept, aside)
173	}
174	if kept, aside, _ := (Scope{Read: read}).Apply(findings); aside.Attributes != 0 || len(kept) != 5 {
175		t.Errorf("without Paths: kept %d aside %+v", len(kept), aside)
176	}
177}