diff options
| author | Frederick Muriuki Muriithi <fredmanglis@gmail.com> | 2026-10-05 14:58:57 -0500 |
|---|---|---|
| committer | Frederick Muriuki Muriithi <fredmanglis@gmail.com> | 2026-10-05 14:58:57 -0500 |
| commit | fe20e4cd95465933ddd7715e9278b9a3cccb9bd0 (patch) | |
| tree | d2ed87e7891a5dcd07f658b09ad7aa01690d40f4 /tests | |
| parent | c30d0b60382fad62e749a4be34ff88ad3c0bc83d (diff) | |
| download | gn-auth-fe20e4cd95465933ddd7715e9278b9a3cccb9bd0.tar.gz | |
Add sanity checks at service initialisation.
We need that there is at least one system administrator defined at service startup. We also verify that the 'GeneNetwork System' resource exists, and is created by the system administrator. If these invariants are not fulfilled, then the service should not run.
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/unit/auth/fixtures/migration_fixtures.py | 18 | ||||
| -rw-r--r-- | tests/unit/auth/fixtures/user_fixtures.py | 27 | ||||
| -rw-r--r-- | tests/unit/auth/test_admin_user_roles.py | 84 | ||||
| -rw-r--r-- | tests/unit/auth/test_groups.py | 13 | ||||
| -rw-r--r-- | tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py | 13 | ||||
| -rw-r--r-- | tests/unit/auth/test_resources.py | 9 | ||||
| -rw-r--r-- | tests/unit/auth/test_roles.py | 2 | ||||
| -rw-r--r-- | tests/unit/conftest.py | 21 |
8 files changed, 119 insertions, 68 deletions
diff --git a/tests/unit/auth/fixtures/migration_fixtures.py b/tests/unit/auth/fixtures/migration_fixtures.py index 954b5a9..1feb279 100644 --- a/tests/unit/auth/fixtures/migration_fixtures.py +++ b/tests/unit/auth/fixtures/migration_fixtures.py @@ -8,14 +8,14 @@ from gn_auth.auth.db import sqlite3 as db from gn_auth.migrations import apply_migrations, rollback_migrations @pytest.fixture(scope="session") -def auth_testdb_path(fxtr_app_config): # pylint: disable=redefined-outer-name +def auth_testdb_path(fxtr_startup_configs): # pylint: disable=redefined-outer-name """Get the test application's auth database file""" - return fxtr_app_config["AUTH_DB"] + return fxtr_startup_configs["AUTH_DB"] @pytest.fixture(scope="session") -def auth_migrations_dir(fxtr_app_config): # pylint: disable=redefined-outer-name +def auth_migrations_dir(fxtr_startup_configs): # pylint: disable=redefined-outer-name """Get the test application's auth database file""" - return fxtr_app_config["AUTH_MIGRATIONS"] + return fxtr_startup_configs["AUTH_MIGRATIONS"] def apply_single_migration(backend: DatabaseBackend, migration: Migration):# pylint: disable=[redefined-outer-name] """Utility to apply a single migration""" @@ -35,6 +35,16 @@ def all_migrations(auth_migrations_dir): # pylint: disable=redefined-outer-name """Retrieve all the migrations""" return read_migrations(auth_migrations_dir) + +@pytest.fixture(scope="session") +def fxtr_apply_all_migrations(backend, all_migrations): + """Apply all the migrations. + + Cannot use the `conn_after_auth_migrations` below due to scope mismatch. + """ + apply_migrations(backend, all_migrations) + + @pytest.fixture(scope="function") def conn_after_auth_migrations(backend, auth_testdb_path, all_migrations): # pylint: disable=redefined-outer-name """Run all migrations and return a connection to the database after""" diff --git a/tests/unit/auth/fixtures/user_fixtures.py b/tests/unit/auth/fixtures/user_fixtures.py index 0872142..3242534 100644 --- a/tests/unit/auth/fixtures/user_fixtures.py +++ b/tests/unit/auth/fixtures/user_fixtures.py @@ -21,6 +21,33 @@ TEST_USERS = ( User(uuid.UUID("60faf8a7-832b-471e-b6a0-bd4013f1fa0e"), "sys@admin.user", "System Admin User", created=_created_)) +@pytest.fixture(scope="session") +def fxtr_basic_setup(auth_testdb_path, fxtr_apply_all_migrations):# pylint: disable=[redefined-outer-name, unused-argument] + admin = User(uuid.UUID("0cb7b0b5-bac4-4359-9ef1-e79c33e5be2a"), + "default@system.admin", "Default System Administrator", + datetime.datetime.fromtimestamp(1691130509.0)) + with (db.connection(auth_testdb_path) as conn, db.cursor(conn) as cursor): + cursor.execute("SELECT resource_id FROM resources " + "WHERE resource_name='GeneNetwork System'") + resource_id = cursor.fetchone()[0] + cursor.execute( + "SELECT role_id FROM roles WHERE role_name='system-administrator'") + role_id = cursor.fetchone()[0] + + cursor.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?)", + (str(admin.user_id), + admin.email, + admin.name, + admin.created.timestamp(), + 1)) + cursor.execute("UPDATE resources SET created_by=?", + (str(admin.user_id),)) + cursor.execute("INSERT INTO user_roles VALUES (?,?,?)", + (str(admin.user_id), role_id, resource_id)) + + yield (admin,) + + @pytest.fixture(scope="function") def fxtr_users(conn_after_auth_migrations):# pylint: disable=[redefined-outer-name, unused-argument] """Fixture: setup test users.""" diff --git a/tests/unit/auth/test_admin_user_roles.py b/tests/unit/auth/test_admin_user_roles.py index 7ce0b1f..1fc4e14 100644 --- a/tests/unit/auth/test_admin_user_roles.py +++ b/tests/unit/auth/test_admin_user_roles.py @@ -38,21 +38,20 @@ def _setup_admin_mock(conn, clients, mocker): @pytest.mark.unit_test -def test_assign_role_no_token_returns_401(fxtr_app): +def test_assign_role_no_token_returns_401(client): """ GIVEN: no Authorization header WHEN: POST /auth/user/<uid>/roles/assign THEN: 401 is returned """ - with fxtr_app.test_client() as http: - res = http.post( - f"/auth/user/{_TARGET_USER.user_id}/roles/assign", - json=_ASSIGN_BODY) + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/assign", + json=_ASSIGN_BODY) assert res.status_code == 401 @pytest.mark.unit_test -def test_assign_role_non_admin_returns_403(fxtr_app, mocker, fxtr_oauth2_clients): +def test_assign_role_non_admin_returns_403(client, mocker, fxtr_oauth2_clients): """ GIVEN: a valid token belonging to a non-admin user WHEN: POST /auth/user/<uid>/roles/assign @@ -65,11 +64,10 @@ def test_assign_role_non_admin_returns_403(fxtr_app, mocker, fxtr_oauth2_clients conftest.get_tokeniser( user, tuple(c for c in clients if c.user == user)[0])) - with fxtr_app.test_client() as http: - res = http.post( - f"/auth/user/{_TARGET_USER.user_id}/roles/assign", - json=_ASSIGN_BODY, - headers={"Authorization": "Bearer some-mocked-token"}) + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/assign", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) assert res.status_code == 403 @@ -91,7 +89,7 @@ def _revoke_assigned_role(conn): @pytest.mark.unit_test -def test_assign_role_admin_returns_200(fxtr_app, mocker, fxtr_oauth2_clients): +def test_assign_role_admin_returns_200(client, mocker, fxtr_oauth2_clients): """ GIVEN: a valid system-admin token and a valid role/resource body WHEN: POST /auth/user/<uid>/roles/assign @@ -100,11 +98,10 @@ def test_assign_role_admin_returns_200(fxtr_app, mocker, fxtr_oauth2_clients): conn, clients = fxtr_oauth2_clients _setup_admin_mock(conn, clients, mocker) try: - with fxtr_app.test_client() as http: - res = http.post( - f"/auth/user/{_TARGET_USER.user_id}/roles/assign", - json=_ASSIGN_BODY, - headers={"Authorization": "Bearer some-mocked-token"}) + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/assign", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) assert res.status_code == 200 finally: _revoke_assigned_role(conn) @@ -139,7 +136,7 @@ def _cleanup_target_role(conn): @pytest.mark.unit_test -def test_assign_role_persists_to_db(fxtr_app, mocker, fxtr_oauth2_clients): +def test_assign_role_persists_to_db(client, mocker, fxtr_oauth2_clients): """ GIVEN: a valid system-admin token and a valid role/resource body WHEN: POST /auth/user/<uid>/roles/assign @@ -148,11 +145,10 @@ def test_assign_role_persists_to_db(fxtr_app, mocker, fxtr_oauth2_clients): conn, clients = fxtr_oauth2_clients _setup_admin_mock(conn, clients, mocker) try: - with fxtr_app.test_client() as http: - http.post( - f"/auth/user/{_TARGET_USER.user_id}/roles/assign", - json=_ASSIGN_BODY, - headers={"Authorization": "Bearer some-mocked-token"}) + client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/assign", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) with db.cursor(conn) as cursor: cursor.execute( "SELECT COUNT(*) AS cnt FROM user_roles " @@ -173,21 +169,20 @@ def test_assign_role_persists_to_db(fxtr_app, mocker, fxtr_oauth2_clients): # --------------------------------------------------------------------------- @pytest.mark.unit_test -def test_revoke_role_no_token_returns_401(fxtr_app): +def test_revoke_role_no_token_returns_401(client): """ GIVEN: no Authorization header WHEN: POST /auth/user/<uid>/roles/revoke THEN: 401 is returned """ - with fxtr_app.test_client() as http: - res = http.post( - f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", - json=_ASSIGN_BODY) + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", + json=_ASSIGN_BODY) assert res.status_code == 401 @pytest.mark.unit_test -def test_revoke_role_non_admin_returns_403(fxtr_app, mocker, fxtr_oauth2_clients): +def test_revoke_role_non_admin_returns_403(client, mocker, fxtr_oauth2_clients): """ GIVEN: a valid token belonging to a non-admin user WHEN: POST /auth/user/<uid>/roles/revoke @@ -200,16 +195,15 @@ def test_revoke_role_non_admin_returns_403(fxtr_app, mocker, fxtr_oauth2_clients conftest.get_tokeniser( user, tuple(c for c in clients if c.user == user)[0])) - with fxtr_app.test_client() as http: - res = http.post( - f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", - json=_ASSIGN_BODY, - headers={"Authorization": "Bearer some-mocked-token"}) + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) assert res.status_code == 403 @pytest.mark.unit_test -def test_revoke_role_admin_returns_200(fxtr_app, mocker, fxtr_oauth2_clients): +def test_revoke_role_admin_returns_200(mocker, client, fxtr_oauth2_clients): """ GIVEN: a valid token with resource:user:assign-role and the target user holds the role on the resource @@ -220,18 +214,17 @@ def test_revoke_role_admin_returns_200(fxtr_app, mocker, fxtr_oauth2_clients): _setup_admin_mock(conn, clients, mocker) _assign_target_role(conn) try: - with fxtr_app.test_client() as http: - res = http.post( - f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", - json=_ASSIGN_BODY, - headers={"Authorization": "Bearer some-mocked-token"}) + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) assert res.status_code == 200 finally: _cleanup_target_role(conn) @pytest.mark.unit_test -def test_revoke_role_removes_from_db(fxtr_app, mocker, fxtr_oauth2_clients): +def test_revoke_role_removes_from_db(client, mocker, fxtr_oauth2_clients): """ GIVEN: a valid token with resource:user:assign-role and the target user holds the role on the resource @@ -242,11 +235,10 @@ def test_revoke_role_removes_from_db(fxtr_app, mocker, fxtr_oauth2_clients): _setup_admin_mock(conn, clients, mocker) _assign_target_role(conn) try: - with fxtr_app.test_client() as http: - http.post( - f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", - json=_ASSIGN_BODY, - headers={"Authorization": "Bearer some-mocked-token"}) + client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) with db.cursor(conn) as cursor: cursor.execute( "SELECT COUNT(*) AS cnt FROM user_roles " diff --git a/tests/unit/auth/test_groups.py b/tests/unit/auth/test_groups.py index 6f1e8cd..93c5af3 100644 --- a/tests/unit/auth/test_groups.py +++ b/tests/unit/auth/test_groups.py @@ -25,10 +25,11 @@ PRIVILEGES = ( "view a resource and use it in computations"), Privilege("group:resource:edit-resource", "edit/update a resource")) + @pytest.mark.unit_test @pytest.mark.parametrize("user", tuple(conftest.TEST_USERS[0:3])) def test_create_group_fails(# pylint: disable=[too-many-arguments too-many-positional-arguments] - fxtr_app, auth_testdb_path, mocker, fxtr_resource_user_roles, fxtr_oauth2_clients, user):# pylint: disable=[unused-argument] + client, auth_testdb_path, mocker, fxtr_resource_user_roles, fxtr_oauth2_clients, user):# pylint: disable=[unused-argument] """ GIVEN: an authenticated user WHEN: the user attempts to create a group @@ -74,7 +75,7 @@ def __cleanup_create_group__(conn, user, group): UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), "a_test_group", {"group_description": "A test group"})),)) def test_create_group_succeeds(# pylint: disable=[too-many-arguments too-many-positional-arguments, unused-argument] - fxtr_app, + client, auth_testdb_path, mocker, fxtr_resource_user_roles, @@ -105,7 +106,7 @@ def test_create_group_succeeds(# pylint: disable=[too-many-arguments too-many-po @pytest.mark.unit_test @pytest.mark.parametrize("user", conftest.TEST_USERS[1:]) def test_create_group_raises_exception_with_non_privileged_user(# pylint: disable=[too-many-arguments too-many-positional-arguments] - fxtr_app, auth_testdb_path, mocker, fxtr_users, fxtr_oauth2_clients, user):# pylint: disable=[unused-argument] + client, auth_testdb_path, mocker, fxtr_users, fxtr_oauth2_clients, user):# pylint: disable=[unused-argument] """ GIVEN: an authenticated user, without appropriate privileges WHEN: the user attempts to create a group @@ -133,7 +134,7 @@ create_role_failure = { "user,expected", tuple(zip(conftest.TEST_USERS[1:], ( create_role_failure, create_role_failure, create_role_failure)))) def test_create_group_role_raises_exception_with_unauthorised_users( - mocker, fxtr_users_in_group, fxtr_oauth2_clients, user, expected): + mocker, client, fxtr_users_in_group, fxtr_oauth2_clients, user, expected): """ GIVEN: an authenticated user WHEN: the user attempts to create a role, attached to a group @@ -153,8 +154,9 @@ def test_create_group_role_raises_exception_with_unauthorised_users( assert create_group_role( conn, GROUP, "ResourceEditor", PRIVILEGES) == expected + @pytest.mark.unit_test -def test_create_multiple_groups(mocker, fxtr_resource_user_roles, fxtr_oauth2_clients): +def test_create_multiple_groups(mocker, client, fxtr_resource_user_roles, fxtr_oauth2_clients): """ GIVEN: An authenticated user with appropriate authorisation WHEN: The user attempts to create a new group, while being a member of an @@ -182,6 +184,7 @@ def test_create_multiple_groups(mocker, fxtr_resource_user_roles, fxtr_oauth2_cl __cleanup_create_group__(conn, user, created_group) + @pytest.mark.unit_test @pytest.mark.parametrize( "user,expected", diff --git a/tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py b/tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py index a32cacb..06f7cf3 100644 --- a/tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py +++ b/tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py @@ -8,7 +8,7 @@ from gn_auth.migrations import get_migration, apply_migrations, rollback_migrati from tests.unit.auth.conftest import ( apply_single_migration, rollback_single_migration, migrations_up_to) -MIGRATION_PATH = "gn_auth/migrations/auth/20221108_04_CKcSL-init-data-in-resource-categories-table.py" +MIGRATION_FILE = "20221108_04_CKcSL-init-data-in-resource-categories-table.py" @pytest.mark.unit_test def test_apply_init_data(auth_testdb_path, auth_migrations_dir, backend): @@ -17,8 +17,9 @@ def test_apply_init_data(auth_testdb_path, auth_migrations_dir, backend): WHEN: The migration is applied THEN: Verify that the expected data exists in the table """ - older_migrations = migrations_up_to(MIGRATION_PATH, auth_migrations_dir) - the_migration = get_migration(MIGRATION_PATH) + migration_path = f"{auth_migrations_dir}/{MIGRATION_FILE}" + older_migrations = migrations_up_to(migration_path, auth_migrations_dir) + the_migration = get_migration(migration_path) apply_migrations(backend, older_migrations) with db.connection(auth_testdb_path, None) as conn, db.cursor(conn) as cursor: cursor.execute("SELECT * FROM resource_categories") @@ -36,6 +37,7 @@ def test_apply_init_data(auth_testdb_path, auth_migrations_dir, backend): rollback_migrations(backend, older_migrations + [the_migration]) + @pytest.mark.unit_test def test_rollback_init_data(auth_testdb_path, auth_migrations_dir, backend): """ @@ -43,8 +45,9 @@ def test_rollback_init_data(auth_testdb_path, auth_migrations_dir, backend): WHEN: The migration is rolled back THEN: Verify that the table is empty """ - older_migrations = migrations_up_to(MIGRATION_PATH, auth_migrations_dir) - the_migration = get_migration(MIGRATION_PATH) + migration_path = f"{auth_migrations_dir}/{MIGRATION_FILE}" + older_migrations = migrations_up_to(migration_path, auth_migrations_dir) + the_migration = get_migration(migration_path) apply_migrations(backend, older_migrations) with db.connection(auth_testdb_path, None) as conn, db.cursor(conn) as cursor: cursor.execute("SELECT * FROM resource_categories") diff --git a/tests/unit/auth/test_resources.py b/tests/unit/auth/test_resources.py index 31dc1c7..23afcef 100644 --- a/tests/unit/auth/test_resources.py +++ b/tests/unit/auth/test_resources.py @@ -34,6 +34,7 @@ create_resource_failure = { conftest.TEST_USERS[0]),)))) def test_create_resource(# pylint: disable=[too-many-arguments, too-many-positional-arguments, unused-argument] mocker, + client, fxtr_users_in_group, fxtr_resource_user_roles, fxtr_oauth2_clients, @@ -74,7 +75,13 @@ def test_create_resource(# pylint: disable=[too-many-arguments, too-many-positio (create_resource_failure, create_resource_failure, create_resource_failure)))) def test_create_resource_raises_for_unauthorised_users( - mocker, fxtr_users_in_group, fxtr_oauth2_clients, user, expected): + mocker, + client, + fxtr_users_in_group, + fxtr_oauth2_clients, + user, + expected +): """Test that resource creation works as expected.""" mocker.patch("gn_auth.auth.authorisation.resources.models.uuid4", conftest.uuid_fn) _conn, clients = fxtr_oauth2_clients diff --git a/tests/unit/auth/test_roles.py b/tests/unit/auth/test_roles.py index b7512ef..6f658ac 100644 --- a/tests/unit/auth/test_roles.py +++ b/tests/unit/auth/test_roles.py @@ -27,7 +27,7 @@ PRIVILEGES = ( "user,expected", tuple(zip(conftest.TEST_USERS[1:], ( create_role_failure, create_role_failure, create_role_failure)))) def test_create_role_raises_exception_for_unauthorised_users(# pylint: disable=[too-many-arguments, unused-argument, too-many-positional-arguments] - fxtr_app, + client, auth_testdb_path, mocker, fxtr_users, diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 53ee062..a43889d 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -20,8 +20,9 @@ def setup_secrets(rootdir: Path) -> Path: @pytest.fixture(scope="session") -def fxtr_app(): - """Fixture: setup the test app""" +def fxtr_startup_configs(): + """Get configs before app is created.""" + import gn_auth.migrations.auth as migrdir # Do some setup testsroot = os.path.dirname(__file__) @@ -30,20 +31,28 @@ def fxtr_app(): f'testdb_{datetime.now().strftime("%Y%m%dT%H%M%S")}') testuploadsdir = Path(testdir).joinpath("uploads") testuploadsdir.mkdir() - app = create_app({ + yield { "TESTING": True, "AUTH_DB": testdb, + "AUTH_MIGRATIONS": str(Path(migrdir.__file__).parent), "GN_AUTH_SECRETS": str(setup_secrets(testdir)), "OAUTH2_ACCESS_TOKEN_GENERATOR": "tests.unit.auth.test_token.gen_token", "UPLOADS_DIR": testuploadsdir, "SSL_PRIVATE_KEY": f"{testsroot}/test-ssl-private-key.pem", "CLIENTS_SSL_PUBLIC_KEYS_DIR": f"{testsroot}/test-public-keys-dir" - }) - app.testing = True - yield app + } + # Clean up after ourselves testdb.unlink(missing_ok=True) + +@pytest.fixture(scope="session") +def fxtr_app(fxtr_basic_setup, fxtr_startup_configs): + """Fixture: setup the test app""" + app = create_app(fxtr_startup_configs) + app.testing = True + return app + @pytest.fixture(scope="session") def client(fxtr_app): # pylint: disable=redefined-outer-name """Create a test client fixture for tests""" |
