Skip to content

Commit 4c907ed

Browse files
committed
Document testing views
1 parent ed028da commit 4c907ed

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

docs/md/testing-views.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Testing views
2+
3+
> [!NOTE]
4+
> This page assumes familiarity with writing automated tests in Python.
5+
6+
When writing tests for Janeway views, rely on the Django test client (`django.test.Client`) unless the nature of your test requires dealing with requests objects explicitly.
7+
8+
Here are tips for avoiding common pitfalls and saving debugging time.
9+
10+
## Use domain mode explicitly
11+
12+
To call the Django test client, you have to write out the URL. But in Janeway, URLs are interpreted differently based on the `URL_CONFIG` setting. `URL_CONFIG` can be set to `"path"` or `"domain"`. In most cases, it is best to set `"domain"` using a setting override in a decorator, so you do not have to write out the journal code or repository short name in the URL.
13+
14+
```py
15+
from django.test import TestCase, override_settings
16+
17+
class MyTest(TestCase):
18+
@override_settings(URL_CONFIG="domain")
19+
def my_test(self):
20+
url = "/profile/"
21+
```
22+
23+
## Name the test server
24+
25+
When Janeway is using domain mode, the domain of the website you are testing (press, journal, repository) becomes important. So it is a good idea to explicitly pass the name of the target domain as `SERVER_NAME` when calling the client.
26+
27+
```py
28+
from django.test import TestCase
29+
30+
class MyTest(TestCase):
31+
def my_test(self):
32+
response = self.client.get(
33+
"/profile/",
34+
SERVER_NAME="www.example.org",
35+
)
36+
```
37+
38+
## When to clear the "script prefix"
39+
40+
In path mode, Janeway makes use of `django.urls.base.set_script_prefix` to insert the journal code into request URLs. However, this path prefix does not go away when another request is made in domain mode. You have to manually clear it by using `clear_script_prefix` in the `tearDown` method of any test case where path mode is used.
41+
42+
```py
43+
from django.urls.base import clear_script_prefix
44+
from django.test import TestCase
45+
46+
class MyTest(TestCase):
47+
def tearDown(self):
48+
clear_script_prefix()
49+
```
50+
51+
If the offending test cannot be found, you can remove the prefix in the `setUp` of any affected test cases.
52+
53+
```py
54+
def setUp(self):
55+
clear_script_prefix()
56+
```
57+
58+
## How to clear the cache
59+
60+
Sometimes a test is affected by cached data. If needed you can clear the main
61+
cache in your setup method or the main test:
62+
63+
```py
64+
from utils.shared import clear_cache
65+
66+
clear_cache()
67+
```

0 commit comments

Comments
 (0)