Testing backend code in Django - django

I am writing an authentication back-end in Django to log only a few users.
It is in a folder called restrictedauthentification/ which is at the root of my Django Project. (I am written it down for a specific project.)
It has two files in it : backend.py and tests.py
In the last file, I have written down some tests for it.
But I can't run them with command ./manage.py test because it isn't an installed app.
Any ideas how I could run them ?

Okay, I found a solution that keep me from turning my backend into a module.
Somthing that I didn't understand and that could help some beginners : In python, a test cannot run itself. It need to be executed by a TestRunner.
Now, one could use the TextTestRunner bundled python that execute the tests and show the results on the standard output, but when testing with django, one need to do one thing before and after the test: calling the function setup_test_environment() and teardown_test_environment().
So I just created a class that inherit from TextTestRunner and redefine its methode run() in order that it execute the two functions provided by Django.
Here it is :
from restrictedauthentification.tests import TestRestrictedAuthentification
from django.test.utils import setup_test_environment, teardown_test_environment
from unittest import TextTestRunner
class DeadSimpleDjangoTestRunner(TextTestRunner):
def run(self, test):
setup_test_environment()
super().run(test)
teardown_test_environment()

Related

Pytest-Variables: how to use them without funcarg?

I wanna pass a json file for testbed definition to pytest.
My testcases are implemented inside a unittest class and need to use the json file send via pytest cli.
I tried to use pytest-variable to pass a json to pytest. Then I want to use the json as a dictionary inside my tests.
To be clearer, my test is launched with this command
pytest -s --variables ../testbeds/testbed_SQA_252.json TC_1418.py
I know unittest cannot accept external arguments but will be very useful a technique to unlock this constraint.
CASE 1 -- test implemented as functions --->OK
def test_variables(variables):
print(variables)
in this case the ouput is correct and the json is printed in the CLI
CASE 2-- test implemented as Unittest Class--->KO
class TC_1418(unittest.TestCase):
def setUp(self, variables):
print (variables)
....other functions
I obtain the following error:
TypeError: setUp() missing 1 required positional argument: 'variables'
Any Idea?
Your issue comes from mixing up concepts of pytest (e.g. injection of fixtures like variables) with concepts of unittest.TestCase. While pytest supports running tests based on unittest, I'm afraid that injection of plugins' fixtures into test methods is not supported.
There is a workaround though that takes advantage of fixtures being injected into other fixtures and making custom fixtures available in unittest.TestCase with #pytest.mark.usefixtures decorator:
# TC_1418.py
import pytest
import unittest
#pytest.fixture(scope="class")
def variables_injector(request, variables):
request.cls.variables = variables
#pytest.mark.usefixtures("variables_injector")
class Test1418(unittest.TestCase):
def test_something(self):
print(self.variables)
Notice that the name of the class starts with Test so as to follow conventions for test discovery.
If you don't want to go into this travesty, I propose you rather fully embrace Pytest and make your life easier with simple test functions that you have already discovered or properly structured test classes:
# TC_1418.py
class Test1418:
def test_something(self, variables):
print(variables)

pytest.mark.parametrize with django.test.SimpleTestCase

I am using pytest 3.2.2 and Django 1.11.5 on Python 3.6.2 on Windows.
The following code
import django.test
import pytest
class ParametrizeTest:
#pytest.mark.parametrize("param", ["a", "b"])
def test_pytest(self, param):
print(param)
assert False
works as expected:
scratch_test.py::ParametrizeTest::test_pytest[a] FAILED
scratch_test.py::ParametrizeTest::test_pytest[b] FAILED
But as soon as I change it to use Django's SimpleTestCase,
like this:
class ParametrizeTest(django.test.SimpleTestCase):
...
it fails with
TypeError: test_pytest() missing 1 required positional argument: 'param'
Can anybody explain why? And what to do against it?
(I actually even need to use django.test.TestCase and access the database.)
I have the following pytest plugins installed:
plugins: random-0.2, mock-1.6.2, django-3.1.2, cov-2.5.1
but turning any one of them (or all of them) off via -p no:random etc. does not help.
The Django test class is a unittest.TestCase subclass.
Parametrization is unsupported and this is documented under the section pytest features in unittest.TestCase subclasses:
The following pytest features do not work, and probably never will due to different design philosophies:
Fixtures (except for autouse fixtures)
Parametrization
Custom hooks
If you need parametrized tests and pytest runner, your best bet is to abandon the unittest style - this means move the setup/teardown into fixtures (pytest-django plugin has already implemented the hard parts for you), and use module level functions for your tests.
Use #pytest.mark.django_db
Thanks, wim, for that helpful answer. RTFM, once again.
For clarity, here is the formulation that will work (equivalent to a test inheriting from TestCase, not just SimpleTestCase).
Make sure you have pytest-django installed and then do:
import pytest
#pytest.mark.django_db
class ParametrizeTest:
#pytest.mark.parametrize("param", ["a", "b"])
def test_pytest(self, param):
print(param)
assert False
(BTW: Funnily, one reason why I originally decided to use pytest was that
the idea of using plain test functions instead of test methods appealed to me;
I like lightweight approaches.
But now I almost exclusively use test classes and methods anyway,
because I prefer the explicit grouping of tests they provide.)

run every TestCase inside a module

How can you run tests from all TestCase classes, in a specific module under tests package?
In a Django project, I have split tests.py under tests/
Each file(module) has several TestCase classes, and each of them having several test methods.
init.py imports each of them.
I already know that I can do these:
Run all the test:
./manage.py test myapp
Or run specific TestCase:
./manage.py test myapp.OneOfManyTestCase
Or run very specific test method from a TestCase class:
./manage.py test myapp.OneOfManyTestCase.test_some_small_method
However, I can't figure out how to run every TestCases from a particular module.
Say, OneOfManyTestCase class is from tests/lot_of_test.py, and there are other test cases too.
Django doesn't seem to care about modules with TestCases.
How can I run all the TestCases inside lot_of_test?
I think to achieve this you need to subclass your own TestRunner from DjangoTestSuiteRunner and override build_suite method.
I ended up writing down my own TestSuiteRunner, like #sneawo said.
After Django-style fails, try importing as usual python-style.
One line to fix:
suite.addTest(build_test(label))
into
try:
suite.addTest(django.test.simple.build_test(label))
except ValueError:
# change to python-style package name
head, tail = label.split('.', 1)
full_label = '.'.join([head, django.test.simple.TEST_MODULE, tail])
# load tests
tests = unittest.defaultTestLoader.loadTestsFromName(full_label)
suite.addTests(tests)
and set TEST_RUNNER in settings.py:
TEST_RUNNER='myapp.tests.module_test_suite_runner.ModuleTestSuiteRunner'

UnitTesting in sikuli - configuration from one place

I would like to ask on UnitTesting in sikuli.
Is there any way to make settings from one place for all test ? Also there are any posibility to import one script (for example login to page) to other test ??
I have serious trouble with that. For example I make import file (config.py) with:
def setUp(self):
...some code...
def tearDown(self):
...some code...
It's really strange because I run test -> it's work,...and after that it didn't.
Do you have same experience? Or how you config your test ...
Thank you.
Because of many odds in the Sikuli IDE implementation of UnitTest (e.g. as in this case: import does not work), I recommend, to generally use the Python UnitTest module directly (just a few lines more coding, but total freedom to do what's needed)
see: https://answers.launchpad.net/sikuli/+faq/1804
I think that there are a few questions that are being asked here. I'll see if I can provide some insights for each.
Is there any way to make settings from one place for all test ?
Like with all unit testing the setUp and tearDown are run before and after each and every unit test.
import one script (for example login to page) to other test ??
Yes, you can reuse code. See the following documentation:
http://doc.sikuli.org/globals.html#importing-other-sikuli-scripts-reuse-code-and-images
I run test -> it's work,...and after that it didn't. Do you have same experience?
To paraphrase the documentation, save before you run and only hit the run button in the unit test panel.
http://sikuli.org/wiki/UnitTesting
Hope this helps.

How do I skip a section of code when unittesting in Django?

In my Django application, I have a section of code that uploads a file to Amazon S3, and I would like to skip this section during unittests. Unittests happen to run with DEBUG=False, so I can't test for settings.DEBUG == True to skip this section. Any ideas?
You really don't want to "skip" code in your unit tests -- if you do, you'll never have coverage for those areas. It's far better to provide a mock interface to external systems, so you can insure that the rest of the code behaves as expected. This is especially critical when dealing with external resources that may be unavailable, as S3 can be in case of network issues, service interruptions, or configuration errors.
Alternately, you could just use the Django S3 storage backend in your production environment, while configuring tests for use local file storage instead.
You could -- and yes, this is a hack -- import the module that does the uploading, and replace the upload function in that module with another function, that does nothing. Something like this:
foo.py:
def bar():
return 42
biz.py:
import foo
print foo.bar() # prints 42
foo.bar = lambda: 37
print foo.bar() # prints 37
Again, it's a hack, but if this is the only place where you're going to need such functionality it might work for you.
You don't skip a function for testing.
You provide a mock implementation for something that you don't want to run as if it were production.
First, you design for testing by making the S3 Uploader a separate class that has exactly the API your application needs.
Then you write a mock version of this class with the same API. All it does is record that it was called.
Finally, you make sure your unit test plugs in your mock object instead of the real S3 Uploader.
Your Django application should not have any changes made -- except the change "injected" into it by the unit test.
Your views.py that does the upload
import the_uploader
import mock_uploader
from django.conf import settings
uploadClass = eval( settings.S3_UPLOAD_CLASS_NAME )
uploader= uploadClass( ... )
Now, you provide two settings.py files. The default settings.py has the proper uploader class name.
For testing, you have a test_settings.py which looks like this.
import settings.py
S3_UPLOAD_CLASS_NAME = "mock_uploader.mock_upload_class"
This allows you to actually test everything.