Skip to content

Commit 2fec9cb

Browse files
authored
Merge pull request #1319 from rdmorganiser/refactor_tests
Refactor tests
2 parents d0f6abe + 405e3e8 commit 2fec9cb

23 files changed

Lines changed: 305 additions & 63 deletions

pyproject.toml

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -229,13 +229,11 @@ parallel = true
229229

230230
[tool.coverage.report]
231231
omit = [
232-
"*/management/*",
232+
"*/management/commands/*",
233233
"*/migrations/*",
234-
"*/tests/*",
235234
]
236235
exclude_lines = [
237-
"raise Exception",
238-
"except ImportError:"
236+
"raise NotImplementedError"
239237
]
240238

241239
[tool.typos] # Ref: https://github.com/crate-ci/typos/blob/master/docs/reference.md

rdmo/conditions/tests/test_viewset_condition.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
'copy': 'v1-conditions:condition-copy'
4242
}
4343

44-
export_formats = ('xml', 'rtf', 'odt', 'docx', 'html', 'markdown', 'tex', 'pdf')
44+
export_formats = ('xml', 'html')
4545

4646

4747
@pytest.mark.parametrize('username,password', users)

rdmo/core/pandoc.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,35 +30,35 @@ def get_pandoc_content(html, metadata, export_format, context):
3030

3131
if metadata:
3232
# create a temporary file for the metadata and close it immediately
33-
metadata_tmp_file_name = create_tmp_file('.json')
33+
metadata_tmp_file_path = create_tmp_file('.json')
3434

3535
# save metadata
36-
log.info('Save metadata file %s %s', metadata_tmp_file_name, str(metadata))
37-
with open(metadata_tmp_file_name, 'w') as fp:
36+
log.info('Save metadata file %s %s', str(metadata_tmp_file_path), str(metadata))
37+
with open(metadata_tmp_file_path, 'w') as fp:
3838
json.dump(metadata, fp)
3939

4040
# add metadata file to pandoc args
41-
pandoc_args.append('--metadata-file=' + metadata_tmp_file_name)
41+
pandoc_args.append(f'--metadata-file={metadata_tmp_file_path}')
4242

4343
# create a temporary file and close it immediately
44-
tmp_file_name = create_tmp_file(f'.{export_format}')
44+
tmp_file_path = create_tmp_file(f'.{export_format}')
4545

4646
# convert the file using pandoc
4747
log.info('Export %s document using args %s.', export_format, pandoc_args)
4848
html = re.sub(
4949
r'(<img.+src=["\'])' + settings.STATIC_URL + r'([\w\-\@?^=%&/~\+#]+)', r'\g<1>' +
5050
str(Path(settings.STATIC_ROOT)) + r'/\g<2>', html
5151
)
52-
pypandoc.convert_text(html, export_format, format='html', outputfile=tmp_file_name, extra_args=pandoc_args)
52+
pypandoc.convert_text(html, export_format, format='html', outputfile=tmp_file_path, extra_args=pandoc_args)
5353

5454
# read the created temporary file
55-
with open(tmp_file_name, 'rb') as fp:
55+
with open(tmp_file_path, 'rb') as fp:
5656
pandoc_content = fp.read()
5757

5858
# delete temporary files
5959
if metadata:
60-
os.remove(metadata_tmp_file_name)
61-
os.remove(tmp_file_name)
60+
os.remove(metadata_tmp_file_path)
61+
os.remove(tmp_file_path)
6262

6363
return pandoc_content
6464

rdmo/core/tests/test_pandoc.py

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@
66

77
from packaging.version import Version
88

9-
from ..pandoc import get_pandoc_args, get_pandoc_reference_document, get_pandoc_reference_documents, get_pandoc_version
9+
from ..pandoc import (
10+
get_pandoc_args,
11+
get_pandoc_content,
12+
get_pandoc_content_disposition,
13+
get_pandoc_reference_document,
14+
get_pandoc_reference_documents,
15+
get_pandoc_version,
16+
)
1017

1118
rdmo_path = Path(apps.get_app_config('rdmo').path)
1219
testing_path = rdmo_path.parent / 'testing'
@@ -65,6 +72,7 @@
6572
class MockedView:
6673
uri = 'http://example.com/terms/views/view'
6774

75+
6876
@pytest.mark.parametrize('pandoc_version', pandoc_versions)
6977
def test_get_pandoc_version(mocker, pandoc_version):
7078
mocker.patch('pypandoc.get_pandoc_version', return_value=pandoc_version)
@@ -75,9 +83,21 @@ def test_get_pandoc_version(mocker, pandoc_version):
7583
@pytest.mark.parametrize('export_format', export_formats)
7684
def test_get_pandoc_args(settings, mocker, pandoc_version, export_format):
7785
mocker.patch('pypandoc.get_pandoc_version', return_value=pandoc_version)
86+
pandoc_args = pandoc_args_map[pandoc_version].get(export_format, pandoc_args_map[pandoc_version]['other'])
87+
88+
assert get_pandoc_args(export_format, {}) == pandoc_args
89+
90+
91+
@pytest.mark.parametrize('pandoc_version', pandoc_versions)
92+
@pytest.mark.parametrize('export_format', export_formats)
93+
def test_get_pandoc_args_resource_path(settings, mocker, pandoc_version, export_format):
94+
mocker.patch('pypandoc.get_pandoc_version', return_value=pandoc_version)
95+
pandoc_args = pandoc_args_map[pandoc_version].get(export_format, pandoc_args_map[pandoc_version]['other']).copy()
96+
97+
if Version(pandoc_version) >= Version('2'):
98+
pandoc_args.append(f'--resource-path={testing_path}/media_root/test')
7899

79-
assert get_pandoc_args(export_format, {}) == \
80-
pandoc_args_map[pandoc_version].get(export_format, pandoc_args_map[pandoc_version]['other'])
100+
assert get_pandoc_args(export_format, {'resource_path': 'test'}) == pandoc_args
81101

82102

83103
def test_get_pandoc_reference_document(mocker):
@@ -154,3 +174,29 @@ def test_get_pandoc_reference_documents_settings(settings, export_format):
154174
assert reference_documents == [mock_file, rdmo_path / 'share' / f'reference.{export_format}']
155175
else:
156176
assert reference_documents == []
177+
178+
179+
@pytest.mark.parametrize('export_format', export_formats)
180+
def test_get_pandoc_content(settings, export_format):
181+
html_path = settings.BASE_DIR / 'export' / 'project.html'
182+
html = html_path.read_text()
183+
184+
metadata = {
185+
'title': 'this is a very nice title',
186+
'author': ['author one', 'author two'],
187+
'keywords': ['nothing', 'something', 'whatever']
188+
}
189+
190+
assert len(get_pandoc_content(html, metadata, export_format, {})) > 0
191+
192+
193+
@pytest.mark.parametrize('export_format', export_formats)
194+
def test_get_pandoc_content_disposition(export_format):
195+
title = 'Test'
196+
197+
if export_format == 'pdf':
198+
content_disposition = f'filename="{title}.{export_format}"'
199+
else:
200+
content_disposition = f'attachment; filename="{title}.{export_format}"'
201+
202+
assert get_pandoc_content_disposition(export_format, 'Test') == content_disposition

rdmo/core/tests/test_utils.py

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,14 @@
55

66
from django.utils.translation import activate
77

8-
from rdmo.core.utils import human2bytes, join_url, parse_date_from_string, sanitize_url
8+
from rdmo.core.utils import (
9+
human2bytes,
10+
join_url,
11+
parse_date_from_string,
12+
parse_metadata,
13+
remove_double_newlines,
14+
sanitize_url,
15+
)
916

1017
urls = (
1118
('', ''),
@@ -46,6 +53,23 @@
4653
(datetime.date(2025, 2, 17), "date must be provided as string")
4754
]
4855

56+
metadata_html = [
57+
('<html><metadata>{"foo": "bar"}</metadata></html>', {'foo': 'bar'}, '<html></html>'),
58+
('<html><metadata>{"f</metadata></html>', None, '<html><metadata>{"f</metadata></html>'),
59+
('<html></html>', None, '<html></html>')
60+
]
61+
62+
double_newline_strings = [
63+
('test\n\n\n\ntest', 'test\n\ntest'),
64+
('test\n\n\ntest', 'test\n\ntest'),
65+
('test\n\ntest', 'test\n\ntest'),
66+
('test\ntest', 'test\ntest'),
67+
]
68+
69+
export_formats = ('xml', 'rtf', 'odt', 'docx', 'html', 'markdown', 'tex', 'pdf')
70+
71+
72+
4973
@pytest.mark.parametrize('url,sanitized_url', urls)
5074
def test_sanitize_url(url, sanitized_url):
5175
assert sanitize_url(url) == sanitized_url
@@ -60,17 +84,27 @@ def test_human2bytes(human: Optional[str], bytes: float):
6084
assert human2bytes(human) == bytes
6185

6286

63-
@pytest.mark.parametrize("locale, date_string, expected_date",valid_date_strings)
87+
@pytest.mark.parametrize("locale, date_string, expected_date", valid_date_strings)
6488
def test_parse_date_from_string_valid_formats(settings, locale, date_string, expected_date):
6589
activate(locale)
6690
assert parse_date_from_string(date_string) == expected_date
6791

6892

69-
@pytest.mark.parametrize("invalid_date, error_msg",invalid_date_strings)
93+
@pytest.mark.parametrize("invalid_date, error_msg", invalid_date_strings)
7094
def test_parse_date_from_string_invalid_formats(settings, invalid_date, error_msg):
7195
if not isinstance(invalid_date,str):
7296
with pytest.raises(TypeError, match=error_msg):
7397
parse_date_from_string(invalid_date)
7498
else:
7599
with pytest.raises(ValueError,match=error_msg):
76100
parse_date_from_string(invalid_date)
101+
102+
103+
@pytest.mark.parametrize('input_html, metadata, output_html', metadata_html)
104+
def test_parse_metadata(input_html, metadata, output_html):
105+
assert parse_metadata(input_html) == (metadata, output_html)
106+
107+
108+
@pytest.mark.parametrize('input_string, output_string', double_newline_strings)
109+
def test_remove_double_newlines(input_string, output_string):
110+
assert remove_double_newlines(input_string) == output_string
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import pytest
2+
3+
from django.urls import reverse
4+
5+
users = (
6+
('editor', 'editor'),
7+
('reviewer', 'reviewer'),
8+
('user', 'user'),
9+
('site', 'site'),
10+
('api', 'api'),
11+
('anonymous', None)
12+
)
13+
14+
status_map = {
15+
'list': {
16+
'editor': 200, 'reviewer': 200, 'user': 403, 'site': 403, 'api': 200, 'anonymous': 401
17+
}
18+
}
19+
20+
urlnames = {
21+
'list': 'v1-core:group-list',
22+
}
23+
24+
25+
@pytest.mark.parametrize('username,password', users)
26+
def test_list(db, client, username, password):
27+
client.login(username=username, password=password)
28+
29+
url = reverse(urlnames['list'])
30+
response = client.get(url)
31+
assert response.status_code == status_map['list'][username], response.json()
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import pytest
2+
3+
from django.urls import reverse
4+
5+
users = (
6+
('editor', 'editor'),
7+
('reviewer', 'reviewer'),
8+
('user', 'user'),
9+
('site', 'site'),
10+
('api', 'api'),
11+
('anonymous', None)
12+
)
13+
14+
status_map = {
15+
'list': {
16+
'editor': 200, 'reviewer': 200, 'user': 403, 'site': 403, 'api': 200, 'anonymous': 401
17+
}
18+
}
19+
20+
urlnames = {
21+
'list': 'v1-core:site-list',
22+
}
23+
24+
25+
@pytest.mark.parametrize('username,password', users)
26+
def test_list(db, client, username, password):
27+
client.login(username=username, password=password)
28+
29+
url = reverse(urlnames['list'])
30+
response = client.get(url)
31+
assert response.status_code == status_map['list'][username], response.json()

rdmo/core/utils.py

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -209,23 +209,6 @@ def import_class(string):
209209
return getattr(importlib.import_module(module_name), class_name)
210210

211211

212-
def copy_model(instance, **kwargs):
213-
# get values from instance which are not id, ForeignKeys or M2M relations
214-
data = {}
215-
for field in instance._meta.get_fields():
216-
if not (field.name == 'id' or field.is_relation):
217-
data[field.name] = getattr(instance, field.name)
218-
219-
# update with the kwargs provided to this function
220-
data.update(kwargs)
221-
222-
# create and save new instance
223-
instance_copy = instance._meta.model(**data)
224-
instance_copy.save()
225-
226-
return instance_copy
227-
228-
229212
def human2bytes(string):
230213
if not string or string == '0':
231214
return 0

rdmo/domain/tests/test_viewset_attribute.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
'copy': 'v1-domain:attribute-copy'
4141
}
4242

43-
export_formats = ('xml', 'csvcomma', 'csvsemicolon', 'rtf', 'odt', 'docx', 'html', 'markdown', 'tex', 'pdf')
43+
export_formats = ('xml', 'html')
4444

4545

4646
@pytest.mark.parametrize('username,password', users)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import pytest
2+
3+
from django.urls import reverse
4+
5+
users = (
6+
('editor', 'editor'),
7+
('reviewer', 'reviewer'),
8+
('user', 'user'),
9+
('site', 'site'),
10+
('api', 'api'),
11+
('anonymous', None)
12+
)
13+
14+
status_map = {
15+
'list': {
16+
'editor': 200, 'reviewer': 200, 'user': 200, 'site': 200, 'api': 200, 'anonymous': 401
17+
}
18+
}
19+
20+
urlnames = {
21+
'list': 'v1-management:meta-list',
22+
}
23+
24+
25+
@pytest.mark.parametrize('username,password', users)
26+
def test_list(db, client, username, password):
27+
client.login(username=username, password=password)
28+
29+
url = reverse(urlnames['list'])
30+
response = client.get(url)
31+
assert response.status_code == status_map['list'][username], response.json()

0 commit comments

Comments
 (0)