Skip to content

Instantly share code, notes, and snippets.

@kyanny
Created December 29, 2020 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyanny/bc7cbf5409b91a965ec4b6682a946e7b to your computer and use it in GitHub Desktop.
Save kyanny/bc7cbf5409b91a965ec4b6682a946e7b to your computer and use it in GitHub Desktop.
Run Django's SimpleTestCase assertion in single Python script (without Django project)
import unittest
from django.test import SimpleTestCase
from django.conf import settings
settings.configure()
class InHTMLTestCase(SimpleTestCase):
databases = []
def test_ok(self):
self.assertInHTML('a', '<div>a</div>')
def test_not_ok(self):
self.assertInHTML('a', '<div>a<br>b</div>')
def test_ok2(self):
self.assertInHTML('a<br>b', '<div>a<br>b</div>')
if __name__ == '__main__':
unittest.main()
@kyanny
Copy link
Author

kyanny commented Dec 29, 2020

~/workspaces/python
❯ python -V
Python 3.6.10

~/workspaces/python
❯ python -m django --version
2.2.13

~/workspaces/python
❯ python t.py -v
test_not_ok (__main__.InHTMLTestCase) ... FAIL
test_ok (__main__.InHTMLTestCase) ... ok
test_ok2 (__main__.InHTMLTestCase) ... ok

======================================================================
FAIL: test_not_ok (__main__.InHTMLTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "t.py", line 14, in test_not_ok
    self.assertInHTML('a', '<div>a<br>b</div>')
  File "/Users/kensuke.nagae/.anyenv/envs/pyenv/versions/3.6.10/lib/python3.6/site-packages/django/test/testcases.py", line 800, in assertInHTML
    self.assertTrue(real_count != 0, msg_prefix + "Couldn't find '%s' in response" % needle)
AssertionError: False is not true : Couldn't find 'a' in response

----------------------------------------------------------------------
Ran 3 tests in 0.053s

FAILED (failures=1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment