Skip to content

Commit 7283ff3

Browse files
authored
Created test for dashboard (#105)
1 parent a6c8551 commit 7283ff3

File tree

8 files changed

+88
-16
lines changed

8 files changed

+88
-16
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,5 @@ build/
2222

2323
test/*.db
2424
test/meta
25+
26+
*.db

config.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616

1717
import os
1818

19-
from utils import env
20-
from distutils.util import strtobool
19+
from utils import env, strtobool
20+
2121

2222
# Application Name
2323
#
@@ -105,4 +105,4 @@
105105
'scope': 'user:login,name',
106106
}
107107

108-
PASSCODE_LENGTH = env('MIN_PASSCODE_LENGTH', 6)
108+
PASSCODE_LENGTH = env('MIN_PASSCODE_LENGTH', 6)

console

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ if __name__ == "__main__":
7171
exit()
7272

7373
if args.sync:
74-
from config import META, DATABASE_URL
74+
from config import DATABASE_URL, META
7575
from elekto.models import meta
7676
from elekto.models.sql import create_session
7777
from elekto.models.utils import sync

elekto/models/sql.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,7 @@
1717
import uuid
1818
import sqlalchemy as S
1919

20-
from sqlalchemy.orm import sessionmaker, scoped_session
21-
from sqlalchemy.ext.declarative import declarative_base
20+
from sqlalchemy.orm import sessionmaker, scoped_session, declarative_base
2221
from sqlalchemy.types import TypeDecorator, CHAR
2322
from sqlalchemy import event
2423

@@ -88,10 +87,11 @@ def update_schema(engine, schema_version):
8887

8988
if db_schema.has_table("election"):
9089
if db_schema.has_table("schema_version"):
91-
db_version = engine.execute('select version from schema_version').scalar()
92-
if db_version is None:
93-
""" intialize the table, if necessary """
94-
engine.execute('insert into schema_version ( version ) values ( 2 )')
90+
with engine.connect() as connection:
91+
db_version = connection.execute(S.text('select version from schema_version')).scalar()
92+
if db_version is None:
93+
""" intialize the table, if necessary """
94+
connection.execute(S.text('insert into schema_version ( version ) values ( 2 )'))
9595
else:
9696
""" new, empty db """
9797
return schema_version
@@ -104,7 +104,7 @@ def update_schema(engine, schema_version):
104104
db_version = update_schema_2(engine)
105105
continue
106106

107-
return db_version;
107+
return db_version
108108

109109

110110
def update_schema_2(engine):
@@ -131,6 +131,9 @@ def update_schema_2(engine):
131131

132132
return 2
133133

134+
def drop_all(url: str):
135+
engine = S.create_engine(url)
136+
BASE.metadata.drop_all(bind=engine)
134137

135138
class UUID(TypeDecorator):
136139
"""Platform-independent UUID type.
@@ -175,7 +178,7 @@ class Version(BASE):
175178

176179
@event.listens_for(Version.__table__, 'after_create')
177180
def create_version(target, connection, **kwargs):
178-
connection.execute(f"INSERT INTO schema_version ( version ) VALUES ( {schema_version} )")
181+
connection.execute(S.text(f"INSERT INTO schema_version ( version ) VALUES ( {schema_version} )"))
179182

180183
class User(BASE):
181184
"""

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ psycopg2==2.9.10
2323
pycparser==2.22
2424
pynacl==1.5.0
2525
pytest==8.3.4
26+
pytest-mock==3.14.0
2627
python-dateutil==2.9.0.post0
2728
python-dotenv==1.0.1
2829
pytz==2024.2

test/test_controllers_elections.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from datetime import datetime, timedelta
2+
from flask.testing import FlaskClient
3+
import pytest
4+
from pytest_mock import MockerFixture
5+
6+
from elekto import APP, SESSION, constants
7+
from elekto.models import meta
8+
from elekto.models.sql import User, drop_all, migrate
9+
10+
@pytest.fixture(scope="module", autouse=True)
11+
def reset_db():
12+
with APP.app_context():
13+
drop_all(APP.config.get('DATABASE_URL'))
14+
15+
16+
@pytest.fixture()
17+
def client():
18+
with APP.app_context():
19+
migrate(APP.config.get('DATABASE_URL'))
20+
yield APP.test_client()
21+
SESSION.close()
22+
drop_all(APP.config.get('DATABASE_URL'))
23+
24+
def test_dashboard(client: FlaskClient):
25+
token="token"
26+
with APP.app_context():
27+
SESSION.add(User(username="carson",
28+
name="Carson Weeks",
29+
token=token,
30+
token_expires_at=datetime.max))
31+
SESSION.commit()
32+
with client.session_transaction() as session:
33+
session[constants.AUTH_STATE] = token
34+
response = client.get("/app")
35+
assert response.status_code == 200
36+
assert b'Welcome! Carson Weeks' in response.data
37+
assert b'Sit back and Relax, there is not to do yet.' in response.data
38+
39+
def test_unauthenticated_dashboard(client: FlaskClient):
40+
with client.session_transaction() as session:
41+
session[constants.AUTH_STATE] = None
42+
response = client.get("/app")
43+
assert response.status_code == 302
44+
45+
def test_elections_running_dashboard(client: FlaskClient, mocker: MockerFixture):
46+
mocker.patch("elekto.meta.Election.where", return_value=[{"name": "Demo Election",
47+
"organization": "kubernetes",
48+
"start_datetime": datetime.min,
49+
"end_datetime": datetime.max}])
50+
token="token"
51+
with APP.app_context():
52+
SESSION.add(User(username="carson",
53+
name="Carson Weeks",
54+
token=token,
55+
token_expires_at=datetime.max))
56+
SESSION.commit()
57+
with client.session_transaction() as session:
58+
session[constants.AUTH_STATE] = token
59+
response = client.get("/app")
60+
assert response.status_code == 200
61+
assert b"Demo Election" in response.data
62+
assert not b"Sit back and Relax, there is not to do yet." in response.data

test/test_core_init.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ def test_schulze_d():
3737
}
3838

3939
result = schulze_d(candidates, ballots)
40-
print(result)
4140
assert result == expected_d
4241

4342
def test_schulze_p():
@@ -67,7 +66,6 @@ def test_schulze_p():
6766
}
6867

6968
result = schulze_p(candidates, d)
70-
print(result)
7169
assert result == expected_p
7270

7371
def test_schulze_rank_simple():

utils.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,15 @@
1818
from dotenv import load_dotenv, set_key
1919

2020
# Load the custom environment file into the program
21-
targetenv = '.env.testing' if os.getenv('TESTING') else '.env'
22-
load_dotenv(os.path.join(os.path.dirname(__file__), targetenv))
21+
isTesting = os.getenv('TESTING') or "PYTEST_VERSION" in os.environ
22+
targetenv = ".env.testing" if isTesting else ".env"
23+
load_dotenv(os.path.join(os.path.dirname(__file__), targetenv), override=True)
2324

25+
def strtobool(value: str) -> bool:
26+
value = value.lower()
27+
if value in ("y", "yes", "on", "1", "true", "t"):
28+
return True
29+
return False
2430

2531
def generate_app_key():
2632
key = os.urandom(32).hex()

0 commit comments

Comments
 (0)