|
| 1 | +""" |
| 2 | +Behave environment setup for Django tests. |
| 3 | +behave-django handles test database setup automatically. |
| 4 | +We just need to add live server and Playwright setup. |
| 5 | +""" |
| 6 | +import os |
| 7 | +from django.contrib.staticfiles.testing import StaticLiveServerTestCase # noqa: E402 |
| 8 | +from playwright.sync_api import sync_playwright # noqa: E402 |
| 9 | + |
| 10 | +# behave-django automatically handles: |
| 11 | +# - Django setup |
| 12 | +# - Test database creation |
| 13 | +# - Database transactions per scenario |
| 14 | + |
| 15 | + |
| 16 | +class LiveServer(StaticLiveServerTestCase): |
| 17 | + """Live server for Behave tests - extends Django's StaticLiveServerTestCase.""" |
| 18 | + |
| 19 | + @classmethod |
| 20 | + def setUpClass(cls): |
| 21 | + """Set up live server - called once for all scenarios.""" |
| 22 | + super().setUpClass() |
| 23 | + os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" |
| 24 | + |
| 25 | + |
| 26 | +def before_all(context): |
| 27 | + """Set up before all tests run.""" |
| 28 | + # Set up live server (behave-django handles test database) |
| 29 | + LiveServer.setUpClass() |
| 30 | + context.live_server_url = LiveServer.live_server_url |
| 31 | + context.live_server_class = LiveServer |
| 32 | + |
| 33 | + # Set up Playwright browser |
| 34 | + os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" |
| 35 | + context.playwright = sync_playwright().start() |
| 36 | + context.browser = context.playwright.chromium.launch(headless=True) |
| 37 | + |
| 38 | + |
| 39 | +def after_all(context): |
| 40 | + """Clean up after all tests run.""" |
| 41 | + # Clean up Playwright |
| 42 | + if hasattr(context, 'browser'): |
| 43 | + context.browser.close() |
| 44 | + if hasattr(context, 'playwright'): |
| 45 | + context.playwright.stop() |
| 46 | + |
| 47 | + # Tear down live server (behave-django handles test database teardown) |
| 48 | + if hasattr(context, 'live_server_class'): |
| 49 | + LiveServer.tearDownClass() |
| 50 | + |
| 51 | + |
| 52 | +def before_scenario(_context, _scenario): |
| 53 | + """Set up before each scenario.""" |
| 54 | + # behave-django automatically handles database transactions per scenario |
| 55 | + pass |
| 56 | + |
| 57 | + |
| 58 | +def after_scenario(context, _scenario): |
| 59 | + """Clean up after each scenario.""" |
| 60 | + # Close the page if it exists |
| 61 | + if hasattr(context, 'page'): |
| 62 | + context.page.close() |
| 63 | + del context.page |
| 64 | + |
| 65 | + # behave-django automatically rolls back database transactions |
0 commit comments