import json import pytest from l4d2web.app import create_app from l4d2web.auth import hash_password from l4d2web.db import init_db, session_scope from l4d2web.models import Blueprint, User @pytest.fixture def user_client_with_blueprints(tmp_path, monkeypatch): db_url = f"sqlite:///{tmp_path/'servers.db'}" monkeypatch.setenv("DATABASE_URL", db_url) app = create_app({"TESTING": True, "DATABASE_URL": db_url, "SECRET_KEY": "test"}) init_db() with session_scope() as session: user = User(username="alice", password_digest=hash_password("secret"), admin=False) session.add(user) session.flush() blueprint_one = Blueprint(user_id=user.id, name="bp1", arguments="[]", config="[]") blueprint_two = Blueprint(user_id=user.id, name="bp2", arguments="[]", config="[]") session.add_all([blueprint_one, blueprint_two]) session.flush() payload = { "user_id": user.id, "blueprint_id": blueprint_one.id, "other_blueprint_id": blueprint_two.id, } client = app.test_client() with client.session_transaction() as sess: sess["user_id"] = payload["user_id"] sess["csrf_token"] = "test-token" return client, payload def test_create_server_from_blueprint(user_client_with_blueprints) -> None: client, data = user_client_with_blueprints payload = {"name": "alpha", "port": 27015, "blueprint_id": data["blueprint_id"]} response = client.post( "/servers", data=json.dumps(payload), content_type="application/json", headers={"X-CSRF-Token": "test-token"}, ) assert response.status_code == 201 def test_reassign_blueprint_anytime(user_client_with_blueprints) -> None: client, data = user_client_with_blueprints create_payload = {"name": "alpha", "port": 27015, "blueprint_id": data["blueprint_id"]} create_response = client.post( "/servers", data=json.dumps(create_payload), content_type="application/json", headers={"X-CSRF-Token": "test-token"}, ) server_id = create_response.get_json()["id"] patch_payload = {"blueprint_id": data["other_blueprint_id"]} response = client.patch( f"/servers/{server_id}", data=json.dumps(patch_payload), content_type="application/json", headers={"X-CSRF-Token": "test-token"}, ) assert response.status_code == 200 def test_lifecycle_form_creates_queued_job(user_client_with_blueprints) -> None: client, data = user_client_with_blueprints create_response = client.post( "/servers", data=json.dumps({"name": "alpha", "port": 27015, "blueprint_id": data["blueprint_id"]}), content_type="application/json", headers={"X-CSRF-Token": "test-token"}, ) server_id = create_response.get_json()["id"] response = client.post( f"/servers/{server_id}/start", headers={"X-CSRF-Token": "test-token"}, ) assert response.status_code == 302 assert response.headers["Location"] == f"/servers/{server_id}"