Browse Source

Fix more lints

Getty Ritter 1 year ago
parent
commit
9b4908c433
9 changed files with 64 additions and 74 deletions
  1. 1 3
      lament-configuration.py
  2. 1 1
      lc/config.py
  3. 22 21
      lc/model.py
  4. 2 2
      scripts/migrate.py
  5. 1 1
      stubs/peewee.py
  6. 1 1
      stubs/pystache/__init__.py
  7. 8 6
      tasks.py
  8. 23 28
      tests/model.py
  9. 5 11
      tests/routes.py

+ 1 - 3
lament-configuration.py

@@ -1,6 +1,4 @@
-import os
-
-from lc.app import app
+from lc.app import app  # noqa: F401
 import lc.config
 import lc.model
 

+ 1 - 1
lc/config.py

@@ -46,7 +46,7 @@ class App:
     def in_memory_db(self):
         try:
             self.db.close()
-        except:
+        except Exception:
             pass
         self.db.init(":memory:")
 

+ 22 - 21
lc/model.py

@@ -1,5 +1,4 @@
 from contextlib import contextmanager
-from dataclasses import dataclass
 import datetime
 import json
 from passlib.apps import custom_app_context as pwd
@@ -34,7 +33,7 @@ class Meta(Model):
     def fetch():
         try:
             return Meta.get(id=0)
-        except:
+        except Exception:
             meta = Meta.create(id=0)
             return meta
 
@@ -107,10 +106,10 @@ class User(Model):
         self, as_user: Optional["User"], page: int
     ) -> Tuple[List[v.Link], v.Pagination]:
         query = Link.select().where(
-            (Link.user == self) & ((self == as_user) | (Link.private == False))
+            (Link.user == self) & ((self == as_user) | (Link.private == False))  # noqa: E712
         )
         links = query.order_by(-Link.created).paginate(page, c.app.per_page)
-        link_views = [l.to_view(as_user) for l in links]
+        link_views = [link.to_view(as_user) for link in links]
         pagination = v.Pagination.from_total(page, query.count())
         return link_views, pagination
 
@@ -143,38 +142,38 @@ class User(Model):
     def import_pinboard_data(self, stream):
         try:
             links = json.load(stream)
-        except json.decoder.JSONDecodeError as exn:
+        except json.decoder.JSONDecodeError:
             raise e.BadFileUpload("could not parse file as JSON")
 
         if not isinstance(links, list):
-            raise e.BadFileUpload(f"expected a list")
+            raise e.BadFileUpload("expected a list")
 
         # create and (for this session) cache the tags
         tags = {}
-        for l in links:
-            if "tags" not in l:
+        for link in links:
+            if "tags" not in link:
                 raise e.BadFileUpload("missing key {exn.args[0]}")
-            for t in l["tags"].split():
+            for t in link["tags"].split():
                 if t in tags:
                     continue
 
                 tags[t] = Tag.get_or_create_tag(self, t)
 
         with self.atomic():
-            for l in links:
+            for link in links:
                 try:
-                    time = datetime.datetime.strptime(l["time"], "%Y-%m-%dT%H:%M:%SZ")
+                    time = datetime.datetime.strptime(link["time"], "%Y-%m-%dT%H:%M:%SZ")
                     ln = Link.create(
-                        url=l["href"],
-                        name=l["description"],
-                        description=l["extended"],
-                        private=l["shared"] == "no",
+                        url=link["href"],
+                        name=link["description"],
+                        description=link["extended"],
+                        private=link["shared"] == "no",
                         created=time,
                         user=self,
                     )
                 except KeyError as exn:
                     raise e.BadFileUpload(f"missing key {exn.args[0]}")
-                for t in l["tags"].split():
+                for t in link["tags"].split():
                     HasTag.get_or_create(link=ln, tag=tags[t])
 
     def get_tags(self) -> List[v.Tag]:
@@ -184,7 +183,9 @@ class User(Model):
         )
 
     def get_related_tags(self, tag: "Tag") -> List[v.Tag]:
-        # SELECT * from has_tag t1, has_tag t2, link l WHERE t1.link_id == l.id AND t2.link_id == l.id AND t1.id != t2.id AND t1 = self
+        # SELECT * from has_tag t1, has_tag t2, link l
+        #   WHERE t1.link_id == l.id AND t2.link_id == l.id
+        #   AND t1.id != t2.id AND t1 = self
         SelfTag = HasTag.alias()
         query = (
             HasTag.select(HasTag.tag)
@@ -206,11 +207,11 @@ class User(Model):
         """
         query = Link.select().where(
             (Link.user == self)
-            & ((self == as_user) | (Link.private == False))
+            & ((self == as_user) | (Link.private == False))  # noqa: E712
             & (Link.name.contains(needle) | Link.description.contains(needle))
         )
         links = query.order_by(-Link.created).paginate(page, c.app.per_page)
-        link_views = [l.to_view(as_user) for l in links]
+        link_views = [link.to_view(as_user) for link in links]
         pagination = v.Pagination.from_total(page, query.count())
         return link_views, pagination
 
@@ -243,7 +244,7 @@ class Link(Model):
     ) -> Tuple[List["Link"], v.Pagination]:
         links = (
             Link.select()
-            .where((Link.user == as_user) | (Link.private == False))
+            .where((Link.user == as_user) | (Link.private == False))  # noqa: E712
             .order_by(-Link.created)
             .paginate(page, c.app.per_page)
         )
@@ -330,7 +331,7 @@ class Tag(Model):
             .join(Link)
             .where(
                 (HasTag.tag == self)
-                & ((HasTag.link.user == as_user) | (HasTag.link.private == False))
+                & ((HasTag.link.user == as_user) | (HasTag.link.private == False))  # noqa: E712
             )
         )
         links = [

+ 2 - 2
scripts/migrate.py

@@ -11,7 +11,7 @@ m.create_tables()
 meta = m.Meta.fetch()
 print(f"Current schema version is: {meta.version}")
 
-import migrations
+import migrations  # noqa: F401, E402
 
 runnable = filter(lambda m: m.version > meta.version, lc.migration.registered)
 
@@ -19,7 +19,7 @@ for migration in sorted(runnable, key=lambda m: m.version):
     print(f"{migration.version} - {migration.name}")
     try:
         migration.run(playhouse.migrate.SqliteMigrator(c.app.db))
-    except:
+    except Exception:
         sys.exit(1)
 
     meta.version = migration.version

+ 1 - 1
stubs/peewee.py

@@ -1,4 +1,4 @@
-from typing import Any, Optional, TypeVar, Type, List
+from typing import Any, Optional, TypeVar, Type
 
 
 class Expression:

+ 1 - 1
stubs/pystache/__init__.py

@@ -1,6 +1,6 @@
 from typing import Any, List
 
-import pystache.loader
+import pystache.loader  # noqa: F401
 
 
 class Renderer:

+ 8 - 6
tasks.py

@@ -16,8 +16,8 @@ def run(c, port=8080, host="127.0.0.1"):
         env={
             "FLASK_APP": "lament-configuration.py",
             "LC_APP_PATH": f"http://{host}:{port}",
-            "LC_DB_PATH": f"test.db",
-            "LC_SECRET_KEY": f"TESTING_KEY",
+            "LC_DB_PATH": "test.db",
+            "LC_SECRET_KEY": "TESTING_KEY",
         },
     )
 
@@ -26,12 +26,12 @@ def run(c, port=8080, host="127.0.0.1"):
 def migrate(c, port=8080, host="127.0.0.1"):
     """Run migrations to update the database schema"""
     c.run(
-        f"PYTHONPATH=$(pwd) poetry run python3 scripts/migrate.py",
+        "PYTHONPATH=$(pwd) poetry run python3 scripts/migrate.py",
         env={
             "FLASK_APP": "lament-configuration.py",
             "LC_APP_PATH": f"http://{host}:{port}",
-            "LC_DB_PATH": f"test.db",
-            "LC_SECRET_KEY": f"TESTING_KEY",
+            "LC_DB_PATH": "test.db",
+            "LC_SECRET_KEY": "TESTING_KEY",
         },
     )
 
@@ -88,5 +88,7 @@ def lint(c):
 def uwsgi(c, sock="lc.sock"):
     """Run a uwsgi server"""
     c.run(
-        f"poetry run uwsgi --socket {sock} --module lament-configuration:app --processes 4 --threads 2"
+        f"poetry run uwsgi --socket {sock} "
+        "--module lament-configuration:app "
+        "--processes 4 --threads 2"
     )

+ 23 - 28
tests/model.py

@@ -1,10 +1,5 @@
-import os
-import peewee
 import pytest
-
-os.environ["LC_DB_PATH"] = ":memory:"
-os.environ["LC_SECRET_KEY"] = "TEST_KEY"
-os.environ["LC_APP_PATH"] = "localhost"
+import config  # noqa: F401
 
 import lc.config as c
 import lc.error as e
@@ -55,9 +50,9 @@ class Testdb:
 
     def test_no_duplicate_users(self):
         name = "gdritter"
-        u1 = self.mk_user(name=name)
+        self.mk_user(name=name)
         with pytest.raises(e.UserExists):
-            u2 = self.mk_user(name=name)
+            self.mk_user(name=name)
 
     def test_get_or_create_tag(self):
         u = self.mk_user()
@@ -104,16 +99,16 @@ class Testdb:
     def test_add_hierarchy(self):
         u = self.mk_user()
         req = r.Link("http://foo.com", "foo", "", False, ["food/bread/rye"])
-        l = m.Link.from_request(u, req)
-        assert l.name == req.name
-        tag_names = {t.tag.name for t in l.tags}  # type: ignore
+        link = m.Link.from_request(u, req)
+        assert link.name == req.name
+        tag_names = {t.tag.name for t in link.tags}  # type: ignore
         assert tag_names == {"food", "food/bread", "food/bread/rye"}
 
     def test_bad_tag(self):
         u = self.mk_user()
         req = r.Link("http://foo.com", "foo", "", False, ["foo{bar}"])
         with pytest.raises(e.BadTagName):
-            l = m.Link.from_request(u, req)
+            m.Link.from_request(u, req)
 
     def test_create_invite(self):
         u = self.mk_user()
@@ -158,32 +153,32 @@ class Testdb:
         with pytest.raises(e.NoSuchInvite):
             m.User.from_invite(r.User(name="u4", password="u4"), "a-non-existent-token")
 
-    def check_tags(self, l, tags):
-        present = set(map(lambda hastag: hastag.tag.name, l.tags))
+    def check_tags(self, link, tags):
+        present = set(map(lambda hastag: hastag.tag.name, link.tags))
         assert present == set(tags)
 
     def test_edit_link(self):
         u = self.mk_user()
 
         req = r.Link("http://foo.com", "foo", "", False, ["foo", "bar"])
-        l = m.Link.from_request(u, req)
-        assert l.name == req.name
-        assert l.tags == ["foo", "bar"]  # type: ignore
+        link = m.Link.from_request(u, req)
+        assert link.name == req.name
+        assert link.tags == ["foo", "bar"]  # type: ignore
 
         # check the in-place update
         req.name = "bar"
         req.tags = ["bar", "baz"]
         req.private = True
-        l.update_from_request(u, req)
-        assert l.name == req.name
-        assert l.private
-        assert l.created != req.created
-        self.check_tags(l, req.tags)
+        link.update_from_request(u, req)
+        assert link.name == req.name
+        assert link.private
+        assert link.created != req.created
+        self.check_tags(link, req.tags)
 
         # check that the link was persisted
-        l2 = m.Link.by_id(l.id)
-        assert l2
-        assert l2.name == req.name
-        assert l2.private
-        assert l2.created != req.created
-        self.check_tags(l2, req.tags)
+        link2 = m.Link.by_id(link.id)
+        assert link2
+        assert link2.name == req.name
+        assert link2.private
+        assert link2.created != req.created
+        self.check_tags(link2, req.tags)

+ 5 - 11
tests/routes.py

@@ -1,10 +1,4 @@
-import os
-import json
-
-os.environ["LC_DB_PATH"] = ":memory:"
-os.environ["LC_SECRET_KEY"] = "TEST_KEY"
-os.environ["LC_APP_PATH"] = "localhost"
-
+import config  # noqa: F401
 import lc.config as c
 import lc.model as m
 import lc.request as r
@@ -35,7 +29,7 @@ class TestRoutes:
     def test_successful_api_login(self):
         username = "gdritter"
         password = "bar"
-        u = self.mk_user(username=username, password=password)
+        self.mk_user(username=username, password=password)
         result = self.app.post("/auth", json={"name": username, "password": password})
         assert result.status == "200 OK"
         decoded_token = c.app.load_token(result.json["token"])
@@ -44,14 +38,14 @@ class TestRoutes:
     def test_failed_api_login(self):
         username = "gdritter"
         password = "bar"
-        u = self.mk_user(username=username, password=password)
+        self.mk_user(username=username, password=password)
         result = self.app.post("/auth", json={"name": username, "password": "foo"})
         assert result.status == "403 FORBIDDEN"
 
     def test_successful_web_login(self):
         username = "gdritter"
         password = "bar"
-        u = self.mk_user(username=username, password=password)
+        self.mk_user(username=username, password=password)
         result = self.app.post(
             "/auth",
             data={"username": username, "password": password},
@@ -62,7 +56,7 @@ class TestRoutes:
     def test_failed_web_login(self):
         username = "gdritter"
         password = "bar"
-        u = self.mk_user(username=username, password=password)
+        self.mk_user(username=username, password=password)
         result = self.app.post("/auth", data={"username": username, "password": "foo"})
         assert result.status == "403 FORBIDDEN"