Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/guides/django.rst
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,29 @@ each worker, and runs better on ``WSGI``.
The ``ASGI`` application of Django has no lifespan, which
:mod:`Pyjo.App.ASGI` notes in the log on ``debug`` and serves it without.

Tests
-----

The tests of the project, which ``manage.py test`` runs, test the static
files, the probes and the routes of :mod:`Pyjoyment` in front of it too, with
:mod:`Pyjo.Test.Pyjo` of the application of ``config/server.py`` in a
``TestCase`` of Django, as :mod:`Pyjo.Test` describes the tests of
:mod:`unittest`.

.. literalinclude:: django/notes/tests.py
:language: python
:caption: notes/tests.py

A request of the test reaches the ``WSGIHandler`` of Django, as one of a
server does, which sends ``request_started`` and ``request_finished``, and so
does the check of the database. Their handler ``close_old_connections``
closes a connection that is not in the autocommit of the settings, as the one
of the transaction of a ``TestCase``, so a query of the view and of the check
fails after it. The test client of Django detaches the handler for its own
requests, and the test detaches it for its class. The test database of SQLite
in memory, the default, hides it, as Django does not close its connection,
and one of PostgreSQL, or of SQLite in a file, shows it.

More
----

Expand Down
39 changes: 39 additions & 0 deletions docs/guides/django/notes/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import Pyjo.Test
import Pyjo.Test.Pyjo

from notes.models import Note

import unittest

from config.server import app
from django.core.signals import request_finished, request_started
from django.db import close_old_connections
from django.test import TestCase


def setUpModule():
unittest.enterModuleContext(Pyjo.Test.raise_failures())


# The requests of Pyjoyment reach the WSGIHandler of Django in the transaction of the test, whose handlers of
# request_started and request_finished would close its connection, so they are detached, as the test client of Django
# detaches them for its own requests
class ServerTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.t = cls.enterClassContext(Pyjo.Test.Pyjo.new(app))
for signal in (request_started, request_finished):
signal.disconnect(close_old_connections)
cls.addClassCleanup(signal.connect, close_old_connections)

def test_notes(self):
Note.objects.create(text='first')
self.t.get_ok('/').status_is(200).content_like(r'^1 notes')
self.t.post_ok('/notes', form={'text': 'second'}).status_is(200).json_is('/notes', ['first', 'second'])

def test_probes(self):
self.t.get_ok('/livez').status_is(200)
self.t.get_ok('/readyz').status_is(200)
self.t.get_ok('/static/notes/notes.css').status_is(404)
self.assertEqual(Note.objects.count(), 0)
10 changes: 9 additions & 1 deletion plugins/pyjoyment/skills/django/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: django
description: Serve an existing Django project, or another WSGI or ASGI application of Python, with the servers of Pyjoyment in the place of gunicorn, uWSGI or uvicorn, as its application mounted on / of a script of Pyjoyment.Lite. Use for config/server.py, Pyjo.IOLoop.blocking for the code of Django outside the application, ASGI with async views, the static files of collectstatic, the probes with a check of the database, the access log, and Pyjo.UserAgent in the views in the place of requests or httpx.
description: Serve an existing Django project, or another WSGI or ASGI application of Python, with the servers of Pyjoyment in the place of gunicorn, uWSGI or uvicorn, as its application mounted on / of a script of Pyjoyment.Lite. Use for config/server.py, Pyjo.IOLoop.blocking for the code of Django outside the application, ASGI with async views, the static files of collectstatic, the probes with a check of the database, the access log, Pyjo.UserAgent in the views in the place of requests or httpx, and the tests of the routes of Pyjoyment in manage.py test.
---

# Django on the servers of Pyjoyment
Expand Down Expand Up @@ -132,6 +132,14 @@ in the skill `deploy`.
database has dropped, and fails every probe until the worker restarts.
- Django sets `TZ` of the process to `TIME_ZONE`, `America/Chicago` by
default, which the time of the logs of Pyjoyment follows.
- A test of the routes of Pyjoyment in `manage.py test`, with
`Pyjo.Test.Pyjo` of the application of `config.server` in a `TestCase`,
fails in the transaction of the test on PostgreSQL, as
`close_old_connections` of `request_started` and `request_finished` closes
its connection: the class detaches it for its requests, as the test client
of Django does, with `signal.disconnect(close_old_connections)` and
`cls.addClassCleanup(signal.connect, close_old_connections)`. SQLite in
memory, the default test database, hides it.

## Documentation

Expand Down
5 changes: 5 additions & 0 deletions plugins/pyjoyment/skills/tests/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,11 @@ PYTHONDEVMODE=1 pyjo-prove -l -r t # and the ResourceWarning of what a test le
- The test client of another framework, or `requests` against a server that
the test starts, has no event loop of the application: `Pyjo.Test.Pyjo`
requests it in the event loop of the test.
- A `Pyjo.UserAgent` of its own, with `ua.server.app = app`, runs an event
loop of its own, where a response that a promise of the application
settles, as `/readyz` of `Health`, does not come on `Pyjo.Reactor.Poll`:
`Pyjo.Test.Pyjo` has its user agent on `Pyjo.IOLoop.singleton`, as a user
agent of `ioloop=Pyjo.IOLoop.singleton` does.
- A test does not request remote hosts: the event `start` of the user agent of
the application sends a request to an application of the test instead, as
`t.app.ua.on('start', lambda ua, tx: ...)` with a new host and port of
Expand Down
39 changes: 39 additions & 0 deletions t/servers/Django.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,45 @@ def asgi(script):
if status == 503:
like_ok(log, r'You cannot call this from an async context', 'SynchronousOnlyOperation')

with subtest('Tests of the project'):
# The tests of the guide in manage.py test, on the test database of SQLite in memory, whose connection Django never
# closes, and in a file, as one of PostgreSQL, whose connection close_old_connections closes in the transaction of
# the test, with the handlers detached and without them
detached = re.compile(r' for signal in \(request_started, request_finished\):\n(?: .*\n){2}')

def test(tmp, reactor, settings):
env = os.environ | {'PYTHONPATH': os.pathsep.join([tmp.to_str(), ROOT.to_str()]), 'PYJO_REACTOR': reactor}
p = subprocess.run(
[PYTHON, 'manage.py', 'test', '--noinput', '--settings', settings],
cwd=tmp.to_str(),
env=env,
capture_output=True,
text=True,
)
return p.stderr.replace('\r\n', '\n'), p.returncode

for reactor in ('Pyjo.Reactor.Asyncio', 'Pyjo.Reactor.Poll'):
with Pyjo.File.tempdir() as tmp:
project(tmp)
tmp.child('config', 'settings_file.py').spew(
"from config.settings import * # noqa: F403\n\nDATABASES['default']['TEST'] = {'NAME': 'test.sqlite3'}\n"
)

for settings in ('config.settings', 'config.settings_file'):
err, code = test(tmp, reactor, settings)
like_ok(err, r'(?m)^Ran 2 tests in .*\n\nOK$', f'{reactor}, {settings}: passed')
is_ok(code, 0, f'{reactor}, {settings}: right exit status')

tests = tmp.child('notes', 'tests.py')
code, count = detached.subn('', tests.slurp().decode())
is_ok(count, 1, 'without the handlers detached')
tests.spew(code)
err, code = test(tmp, reactor, 'config.settings_file')
like_ok(err, r'(?m)^ +got: 500$', f'{reactor}: the connection closed in the view')
like_ok(err, r'(?m)^ +got: 503$', f'{reactor}: and in the check of the database')
like_ok(err, r'(?m)^FAILED \(failures=2\)$', f'{reactor}: failed')
is_ok(code, 1, f'{reactor}: right exit status')

with subtest('ASGI'):
with Pyjo.File.tempdir() as tmp:
project(tmp)
Expand Down
Loading