Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use fixtures from other apps in django's tests?

I have 2 apps, members and resources. resources depends on members. Is it possible to use test fixtures from the members app in my tests for the resources app?

like image 656
Thomas Avatar asked Sep 06 '11 04:09

Thomas


People also ask

Can a Pytest fixture be a test?

Pytest fixtures are functions that can be used to manage our apps states and dependencies. Most importantly, they can provide data for testing and a wide range of value types when explicitly called by our testing software. You can use the mock data that fixtures create across multiple tests.

How does fixture work in Pytest?

Fixtures define the steps and data that constitute the arrange phase of a test (see Anatomy of a test). In pytest, they are functions you define that serve this purpose. They can also be used to define a test's act phase; this is a powerful technique for designing more complex tests.

How do you use fixtures?

To access the fixture function, the tests have to mention the fixture name as input parameter. Pytest while the test is getting executed, will see the fixture name as input parameter. It then executes the fixture function and the returned value is stored to the input parameter, which can be used by the test.

How do I load all fixtures in Django?

By default, Django only loads fixtures into the default database. Use before_scenario to load the fixtures in all of the databases you have configured if your tests rely on the fixtures being loaded in all of them.


2 Answers

Apparently yes, any fixture can be loaded from any app as if it was in the same app, so be wary of what you name your fixtures. :/

like image 173
Thomas Avatar answered Sep 23 '22 00:09

Thomas


For example, if you have two apps, one named for "App1" and the other named "App2", and the structure of your project is something like this:

myproject/
----APP1/
--------models/
------------app_1_model.py
--------tests/
------------test_app1.py
--------fixtures/
------------fixture_app1_number_1.json
------------fixture_app1_number_2.json
----APP2/
--------models/
------------app_2_model.py
--------tests/
------------test_app2.py
--------fixtures/
------------fixture_app2_number_1.json
------------fixture_app2_number_2.json
------------fixture_app2_number_3.json

this is a imaginary scenario, and you want to write test script for "APP2" but your test script may need the data from "APP1", in other words you need the fixtures in "APP1"

from APP1.models.app_1_model import *
class TestApp2(TestCase):
   fixtures = ['fixture_app2_number_1','fixture_app2_number_2','fixture_app2_number_3','fixture_app1_number_1']
   def test_function_one(self):
     pass

as you saw, just write the fixture name of "APP1" in the fixtures list, very intelligent and easy.

like image 40
tolerious Avatar answered Sep 23 '22 00:09

tolerious