-
Notifications
You must be signed in to change notification settings - Fork 4
/
conftest.py
2264 lines (1816 loc) · 69.9 KB
/
conftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import contextlib
from dataclasses import dataclass
from functools import partial
from typing import Any
from typing import Callable
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Type
from unittest.mock import MagicMock
from unittest.mock import patch
import boto3
import factory
import pytest
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.management import create_contenttypes
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import DEFAULT_DB_ALIAS
from django.test.client import RequestFactory
from django.test.html import parse_html
from django.urls import reverse
from factory.django import DjangoModelFactory
from lxml import etree
from moto import mock_s3
from pytest_bdd import given
from pytest_bdd import parsers
from pytest_bdd import then
from rest_framework.test import APIClient
from checks.tests.factories import TransactionCheckFactory
from common.business_rules import BusinessRule
from common.business_rules import BusinessRuleViolation
from common.business_rules import UpdateValidity
from common.business_rules import ValidityPeriodContained
from common.models import TrackedModel
from common.models.transactions import Transaction
from common.models.transactions import TransactionPartition
from common.models.utils import override_current_transaction
from common.serializers import TrackedModelSerializer
from common.tariffs_api import Endpoints
from common.tests import factories
from common.tests.models import model_with_history
from common.tests.util import Dates
from common.tests.util import assert_records_match
from common.tests.util import export_workbasket
from common.tests.util import generate_test_import_xml
from common.tests.util import get_form_data
from common.tests.util import make_duplicate_record
from common.tests.util import make_non_duplicate_record
from common.tests.util import raises_if
from common.validators import ApplicabilityCode
from common.validators import UpdateType
from importer.models import ImportBatchStatus
from importer.nursery import get_nursery
from importer.taric import process_taric_xml_stream
from measures.duty_sentence_parser import DutySentenceParser as LarkDutySentenceParser
from measures.models import DutyExpression
from measures.models import MeasureConditionComponent
from measures.models import Measurement
from measures.models import MeasurementUnit
from measures.models import MeasurementUnitQualifier
from measures.models import MonetaryUnit
from measures.parsers import DutySentenceParser
from publishing.models import PackagedWorkBasket
from tasks.models import UserAssignment
from workbaskets.models import WorkBasket
from workbaskets.models import get_partition_scheme
from workbaskets.validators import WorkflowStatus
def pytest_addoption(parser):
parser.addoption(
"--hmrc-live-api",
action="store_true",
help="Test will call the live HMRC Sandbox API and not mock the request.",
)
def pytest_configure(config):
config.addinivalue_line(
"markers",
"hmrc_live_api: mark test calling the live HMRC Sandbox API",
)
def pytest_runtest_setup(item):
if "hmrc_live_api" in item.keywords and not item.config.getoption(
"--hmrc-live-api",
):
pytest.skip("Not calling live HMRC Sandbox API. Use --hmrc-live-api to do so.")
def pytest_bdd_apply_tag(tag, function):
if tag == "todo":
marker = pytest.mark.skip(reason="Not implemented yet")
marker(function)
return True
if tag == "xfail":
marker = pytest.mark.xfail()
marker(function)
return True
@pytest.fixture(scope="session", autouse=True)
def celery_config():
return {
"broker_url": "memory://",
"result_backend": "cache",
"cache_backend": "memory",
"task_always_eager": True,
}
@pytest.fixture(
params=(
("normal", "normal", True),
("normal", "overlap_normal", False),
("overlap_normal", "normal", False),
("big", "normal", True),
("later", "normal", False),
),
ids=(
"equal_dates",
"overlaps_end",
"overlaps_start",
"contains",
"no_overlap",
),
)
def spanning_dates(request, date_ranges):
"""Returns a pair of date ranges for a container object and a contained
object, and a flag indicating whether the container date ranges completely
spans the contained date range."""
container_validity, contained_validity, container_spans_contained = request.param
return (
getattr(date_ranges, container_validity),
getattr(date_ranges, contained_validity),
container_spans_contained,
)
@pytest.fixture
def tap_migrator_factory(migrator_factory):
"""
This fixture is an override of the django-test-migrations fixture of
`django_test_migrations.contrib.pytest_plugin.migrator_factory()`.
One or two issues in Django, and / or related libraries that TAP uses for
its migration unit testing, continues to cause problems in migration unit
tests. A couple of examples of the reported issue:
https://code.djangoproject.com/ticket/10827
/PS-IGNORE---https://github.com/wemake-services/django-test-migrations/blob/93db540c00a830767eeab5f90e2eef1747c940d4/django_test_migrations/migrator.py#L73
An initial migration must reference ContentType instances (in the DB). This
can occur when inserting Permission objects during
`migrator.apply_initial_migration()` execution.
At that point, a stale ContentType cache can give an incorrect account of
ContentType DB table state, so attempts by an initial migration to insert
those Permission objects fails on foreign key violations because they're
referencing missing ContentType objects (they're not in the database, only
in the ContentType cache).
"""
ContentType.objects.clear_cache()
return migrator_factory
@pytest.fixture
def migrator(tap_migrator_factory):
"""Override of `django_test_migrations.contrib.pytest_plugin.migrator()`,
substituting a call to
`django_test_migrations.contrib.pytest_plugin.migrator_factory()` with a
locally overriden instance, `tap_migrator_factory()`."""
return tap_migrator_factory(DEFAULT_DB_ALIAS)
@pytest.fixture
def setup_content_types():
"""This fixture is used to set-up content types, needed for migration
testing, when a clean new database and the content types have not been
populated yet."""
def _method(apps):
tamato_apps = settings.DOMAIN_APPS + settings.TAMATO_APPS
app_labels = []
for app in apps.get_app_configs():
app_labels.append(app.label)
for app_name in tamato_apps:
app_label = app_name.split(".")[0]
if app_label in app_labels:
app_config = apps.get_app_config(app_label)
app_config.models_module = True
create_contenttypes(app_config)
return _method
@pytest.fixture
def assert_spanning_enforced(spanning_dates, update_type):
"""
Provides a function that thoroughly checks if the validity period of a
contained object is enforced to be within the validity period of a container
object.
In particular it also checks that the passed business rule doesn't take into
account deleted contained items in its enforcement, and that it always uses
the latest version of related objects.
This is useful in implementing tests for business rules of the form:
When a "contained object" is used in a "container object" the validity
period of the "container object" must span the validity period of the
"contained object".
"""
def check(
factory: Type[DjangoModelFactory],
business_rule: Type[ValidityPeriodContained],
**factory_kwargs,
):
container_validity, contained_validity, fully_spanned = spanning_dates
contained = getattr(business_rule, "contained_field_name") or ""
container = getattr(business_rule, "container_field_name") or ""
# If the test is checking an UPDATE or a DELETE, set the dates to be
# valid on the original version so that we can tell if it is
# successfully checking the later version.
validity_on_contained = (
container_validity
if update_type != UpdateType.CREATE
else contained_validity
)
object = factory.create(
**factory_kwargs,
**{
f"{contained}{'__' if contained else ''}valid_between": validity_on_contained,
f"{contained}{'__' if contained else ''}update_type": UpdateType.CREATE,
f"{container}{'__' if container else ''}valid_between": container_validity,
},
)
workbasket = object.transaction.workbasket
if update_type != UpdateType.CREATE:
# Make a new version of the contained model with the actual dates we
# are testing, first finding the correct contained model to use.
contained_obj = object
if contained:
with override_current_transaction(workbasket.current_transaction):
contained_obj = (
object.get_versions().current().follow_path(contained).get()
)
contained_obj.new_version(
workbasket,
valid_between=contained_validity,
update_type=update_type,
)
error_expected = update_type != UpdateType.DELETE and not fully_spanned
with raises_if(business_rule.Violation, error_expected):
business_rule(workbasket.current_transaction).validate(object)
return check
@pytest.fixture
def date_ranges() -> Dates:
return Dates()
@pytest.fixture
def api_client() -> APIClient:
return APIClient()
@pytest.fixture
def policy_group(db) -> Group:
group = factories.UserGroupFactory.create(name="Policy")
for app_label, codename in [
("common", "add_trackedmodel"),
("common", "change_trackedmodel"),
("workbaskets", "add_workbasket"),
("workbaskets", "change_workbasket"),
("workbaskets", "view_workbasket"),
("publishing", "consume_from_packaging_queue"),
("publishing", "manage_packaging_queue"),
("publishing", "view_envelope"),
("tasks", "add_userassignment"),
("tasks", "change_userassignment"),
("tasks", "add_comment"),
("tasks", "view_comment"),
("tasks", "change_comment"),
("tasks", "delete_comment"),
]:
group.permissions.add(
Permission.objects.get(
content_type__app_label=app_label,
codename=codename,
),
)
return group
@pytest.fixture
def valid_user(db, policy_group):
user = factories.UserFactory.create()
policy_group.user_set.add(user)
return user
@pytest.fixture
def valid_user_client(client, valid_user):
client.force_login(valid_user)
return client
@pytest.fixture
def client_with_current_workbasket(client, valid_user):
client.force_login(valid_user)
workbasket = factories.WorkBasketFactory.create(
status=WorkflowStatus.EDITING,
)
workbasket.set_as_current(valid_user)
return client
@pytest.fixture
def client_with_current_workbasket_no_permissions(client):
"""Returns a client with a logged in user who has a current workbasket but
no permissions."""
user = factories.UserFactory.create()
client.force_login(user)
workbasket = factories.WorkBasketFactory.create(
status=WorkflowStatus.EDITING,
)
workbasket.set_as_current(user)
return client
@pytest.fixture
def superuser():
user = factories.UserFactory.create(is_superuser=True, is_staff=True)
return user
@pytest.fixture
def superuser_client(client, superuser):
client.force_login(superuser)
return client
@pytest.fixture
@given(parsers.parse("a valid user named {username}"), target_fixture="a_valid_user")
def a_valid_user(username):
return factories.UserFactory.create(username=username)
@given(parsers.parse("I am logged in as {username}"), target_fixture="logged_in")
def logged_in(client, username):
user = get_user_model().objects.get(username=username)
client.force_login(user)
@given(
parsers.parse("{username} is in the Policy group"),
target_fixture="user_in_policy_group",
)
def user_in_policy_group(client, policy_group, username):
user = get_user_model().objects.get(username=username)
policy_group.user_set.add(user)
@pytest.fixture
def valid_user_api_client(api_client, valid_user) -> APIClient:
api_client.force_login(valid_user)
return api_client
@pytest.fixture
def api_client_with_current_workbasket(api_client, valid_user) -> APIClient:
api_client.force_login(valid_user)
workbasket = factories.WorkBasketFactory.create(
status=WorkflowStatus.EDITING,
)
workbasket.set_as_current(valid_user)
return api_client
@pytest.fixture
def taric_schema(settings) -> etree.XMLSchema:
with open(settings.PATH_XSD_TARIC) as xsd_file:
return etree.XMLSchema(etree.parse(xsd_file))
@pytest.fixture
def new_workbasket() -> WorkBasket:
workbasket = factories.WorkBasketFactory.create(
status=WorkflowStatus.EDITING,
)
with factories.TransactionFactory.create(workbasket=workbasket):
factories.FootnoteTypeFactory.create_batch(2)
return workbasket
@pytest.fixture
def assigned_workbasket() -> WorkBasket:
workbasket = factories.AssignedWorkBasketFactory.create()
with factories.TransactionFactory.create(workbasket=workbasket):
factories.FootnoteTypeFactory.create_batch(2)
return workbasket
@pytest.fixture
def queued_workbasket():
return factories.QueuedWorkBasketFactory.create()
@pytest.fixture
def published_additional_code_type(queued_workbasket):
return factories.AdditionalCodeTypeFactory(
transaction=queued_workbasket.new_transaction(),
)
@pytest.fixture
def published_certificate_type(queued_workbasket):
return factories.CertificateTypeFactory(
transaction=queued_workbasket.new_transaction(),
)
@pytest.fixture
def published_footnote_type(queued_workbasket):
return factories.FootnoteTypeFactory(
transaction=queued_workbasket.new_transaction(),
)
@pytest.fixture
@given("there is a current workbasket")
def user_workbasket(client, valid_user, assigned_workbasket) -> WorkBasket:
"""Returns a workbasket which has been assigned to a valid logged-in
user."""
client.force_login(valid_user)
assigned_workbasket.set_as_current(valid_user)
return assigned_workbasket
@pytest.fixture
def user_empty_workbasket(client, valid_user) -> WorkBasket:
client.force_login(valid_user)
workbasket = factories.WorkBasketFactory.create(
status=WorkflowStatus.EDITING,
)
workbasket.set_as_current(valid_user)
return workbasket
@pytest.fixture
def queued_workbasket_factory():
def factory_method():
workbasket = factories.WorkBasketFactory.create(
status=WorkflowStatus.QUEUED,
)
with factories.ApprovedTransactionFactory.create(workbasket=workbasket):
factories.FootnoteTypeFactory()
factories.AdditionalCodeFactory()
return workbasket
return factory_method
@pytest.fixture
def published_workbasket_factory():
def factory_method():
workbasket = factories.PublishedWorkBasketFactory()
with factories.ApprovedTransactionFactory.create(workbasket=workbasket):
factories.FootnoteTypeFactory()
factories.AdditionalCodeFactory()
return workbasket
return factory_method
@pytest.fixture(scope="function")
def seed_file_transaction():
return factories.SeedFileTransactionFactory.create()
@pytest.fixture(scope="function")
def approved_transaction():
return factories.ApprovedTransactionFactory.create()
@pytest.fixture(scope="function")
def unapproved_transaction():
return factories.UnapprovedTransactionFactory.create()
@pytest.fixture(scope="function")
def unapproved_checked_transaction(unapproved_transaction):
TransactionCheckFactory.create(
transaction=unapproved_transaction,
completed=True,
successful=True,
)
return unapproved_transaction
@pytest.fixture(scope="function")
def workbasket():
"""
Returns existing workbasket if one already exists otherwise creates a new
one.
This is as some tests already have a workbasket when this is called.
"""
if WorkBasket.objects.all().count() > 0:
workbasket = WorkBasket.objects.first()
else:
workbasket = factories.WorkBasketFactory.create()
task = factories.TaskFactory.create(workbasket=workbasket)
factories.UserAssignmentFactory.create(
assignment_type=UserAssignment.AssignmentType.WORKBASKET_WORKER,
task=task,
)
factories.UserAssignmentFactory.create(
assignment_type=UserAssignment.AssignmentType.WORKBASKET_REVIEWER,
task=task,
)
return workbasket
@pytest.fixture(
params=factories.TrackedModelMixin.__subclasses__(),
ids=[
factory._meta.model.__name__
for factory in factories.TrackedModelMixin.__subclasses__()
],
)
def trackedmodel_factory(request):
"""Fixture that provides every TrackedModel class."""
return request.param
@pytest.fixture(
params=factories.ValidityFactoryMixin.__subclasses__(),
ids=[
factory._meta.model.__name__
for factory in factories.ValidityFactoryMixin.__subclasses__()
],
)
def validity_factory(request):
return request.param
@pytest.fixture(
params=(
factories.AdditionalCodeDescriptionFactory,
factories.CertificateDescriptionFactory,
factories.GeographicalAreaDescriptionFactory,
factories.GoodsNomenclatureDescriptionFactory,
factories.FootnoteDescriptionFactory,
factories.TestModelDescription1Factory,
),
)
def description_factory(request):
return request.param
@pytest.fixture
def use_create_form(api_client_with_current_workbasket):
"""
use_create_form, ported from use_update_form.
use_create_form works with the model class, unlike use_update_from which
works from an instance of a model class.
Because this function creates data there is no initial instance to inspect
so the implementation cannot use helpers that rely on a model instance like
get_identifying_fields to build its data.
Where practical this raises the same or equivalent assertions as
use_update_form
"""
def use(
Model: Type[TrackedModel],
new_data: Callable[[Dict[str, str]], Dict[str, str]],
):
"""
:param Model: Model class to test
:param new_data function to populate form initial data.
"""
prefix = Model.get_url_pattern_name_prefix()
# Prefix will be along the lines of additional_code
create_url = reverse(f"{prefix}-ui-create")
assert create_url, f"No create page found for {Model}"
# Initial rendering of url
response = api_client_with_current_workbasket.get(create_url)
assert response.status_code == 200
initial_form = response.context_data["form"]
data = get_form_data(initial_form)
# Submit the edited data and if we expect success ensure we are redirected
realised_data = new_data(data)
data.update(realised_data)
# There is no model instance to fetch identifying_fields from, construct
# them from the provided form data.
identifying_values = {
k: data.get(k) for k in Model.identifying_fields if "__" not in k
}
response = api_client_with_current_workbasket.post(create_url, data)
# Check that if we expect failure that the new data was not persisted
if response.status_code not in (301, 302):
assert not Model.objects.filter(**identifying_values).exists()
raise ValidationError(
f"Create form contained errors: {dict(response.context_data['form'].errors)}",
)
new_version = Model.objects.filter(**identifying_values).get()
# Check that the new version is an update and is not approved yet
assert new_version.update_type == UpdateType.CREATE
assert not new_version.transaction.workbasket.approved
return new_version
return use
@pytest.fixture
def use_edit_view(api_client_with_current_workbasket):
"""
Uses the default edit form and view for a model in a workbasket with EDITING
status.
The ``object`` param is the TrackedModel instance that is to be edited and
saved, which should not create a new version.
``data_changes`` should be a dictionary to apply to the object, effectively
applying edits.
Will raise :class:`~django.core.exceptions.ValidationError` if the form
contains errors.
"""
def use(obj: TrackedModel, data_changes: dict[str, str]):
Model = type(obj)
obj_count = Model.objects.filter(**obj.get_identifying_fields()).count()
url = obj.get_url("edit")
# Check initial form rendering.
get_response = api_client_with_current_workbasket.get(url)
assert get_response.status_code == 200
# Edit and submit the data.
initial_form = get_response.context_data["form"]
form_data = get_form_data(initial_form)
form_data.update(data_changes)
post_response = api_client_with_current_workbasket.post(url, form_data)
# POSTing a real edits form should never create new object instances.
assert Model.objects.filter(**obj.get_identifying_fields()).count() == obj_count
if post_response.status_code not in (301, 302):
raise ValidationError(
f"Form contained errors: {dict(post_response.context_data['form'].errors)}",
)
return use
@pytest.fixture
def use_edit_view_no_workbasket(valid_user_api_client):
"""
Uses the default edit form and view for a model in a workbasket with EDITING
status.
The ``object`` param is the TrackedModel instance that is to be edited and
saved, which should not create a new version.
``data_changes`` should be a dictionary to apply to the object, effectively
applying edits.
Will raise :class:`~django.core.exceptions.ValidationError` if the form
contains errors.
"""
def use(obj: TrackedModel, data_changes: dict[str, str]):
Model = type(obj)
obj_count = Model.objects.filter(**obj.get_identifying_fields()).count()
url = obj.get_url("edit")
# Check initial form rendering.
get_response = valid_user_api_client.get(url)
assert get_response.status_code == 200
# Edit and submit the data.
initial_form = get_response.context_data["form"]
form_data = get_form_data(initial_form)
form_data.update(data_changes)
post_response = valid_user_api_client.post(url, form_data)
# POSTing a real edits form should never create new object instances.
assert Model.objects.filter(**obj.get_identifying_fields()).count() == obj_count
if post_response.status_code not in (301, 302):
raise ValidationError(
f"Form contained errors: {dict(post_response.context_data['form'].errors)}",
)
return use
@pytest.fixture
def use_update_form(api_client_with_current_workbasket):
"""
Uses the default create form and view for a model with update_type=UPDATE.
The ``object`` param is the TrackedModel instance for which a new UPDATE
instance is to be created.
The ``new_data`` dictionary should contain callable objects that when passed
the existing value will return a new value to be sent with the form.
Will raise :class:`~django.core.exceptions.ValidationError` if form thinks
that the passed data contains errors.
"""
def use(object: TrackedModel, new_data: Callable[[TrackedModel], dict[str, Any]]):
model = type(object)
versions = set(
model.objects.filter(**object.get_identifying_fields()).values_list(
"pk",
flat=True,
),
)
# Visit the edit page and ensure it is a success
edit_url = object.get_url("edit")
assert edit_url, f"No edit page found for {object}"
response = api_client_with_current_workbasket.get(edit_url)
assert response.status_code == 200
# Get the data out of the edit page
# and override it with any data that has been passed in
data = get_form_data(response.context_data["form"])
# Submit the edited data and if we expect success ensure we are redirected
realised_data = new_data(object)
assert set(realised_data.keys()).issubset(data.keys())
data.update(realised_data)
response = api_client_with_current_workbasket.post(edit_url, data)
# Check that if we expect failure that the new data was not persisted
if response.status_code not in (301, 302):
assert (
set(
model.objects.filter(**object.get_identifying_fields()).values_list(
"pk",
flat=True,
),
)
== versions
)
raise ValidationError(
f"Update form contained errors: {response.context_data['form'].errors}",
)
# Check that what we asked to be changed has been persisted
response = api_client_with_current_workbasket.get(edit_url)
assert response.status_code == 200
data = get_form_data(response.context_data["form"])
for key in realised_data:
assert data[key] == realised_data[key]
# Check that if success was expected that the new version was persisted
new_version = model.objects.exclude(pk=object.pk).get(
version_group=object.version_group,
)
assert new_version != object
# Check that the new version is an update and is not approved yet
assert new_version.update_type == UpdateType.UPDATE
assert new_version.transaction != object.transaction
assert not new_version.transaction.workbasket.approved
return new_version
return use
@pytest.fixture
def use_delete_form(api_client_with_current_workbasket):
"""
Uses the default delete form and view for a model to delete an object, and
returns the deleted version of the object.
Will raise :class:`~django.core.exceptions.ValidationError` if form thinks
that the object cannot be deleted..
"""
def use(object: TrackedModel):
model = type(object)
versions = set(
model.objects.filter(**object.get_identifying_fields()).values_list(
"pk",
flat=True,
),
)
# Visit the delete page and ensure it is a success
delete_url = object.get_url("delete")
assert delete_url, f"No delete page found for {object}"
response = api_client_with_current_workbasket.get(delete_url)
assert response.status_code == 200
# Get the data out of the delete page
data = get_form_data(response.context_data["form"])
response = api_client_with_current_workbasket.post(delete_url, data)
# Check that if we expect failure that the new data was not persisted
if response.status_code not in (301, 302):
assert (
set(
model.objects.filter(**object.get_identifying_fields()).values_list(
"pk",
flat=True,
),
)
== versions
)
raise ValidationError(
f"Delete form contained errors: {response.context_data['form'].errors}",
)
# Check that the delete persisted and we can't delete again
response = api_client_with_current_workbasket.get(delete_url)
assert response.status_code == 404
# Check that if success was expected that the new version was persisted
new_version = model.objects.exclude(pk=object.pk).get(
version_group=object.version_group,
)
assert new_version != object
# Check that the new version is a delete and is not approved yet
assert new_version.update_type == UpdateType.DELETE
assert new_version.transaction != object.transaction
assert not new_version.transaction.workbasket.approved
return new_version
return use
@pytest.fixture
def import_xml(valid_user):
def run_import(xml, workflow_status=WorkflowStatus.PUBLISHED, record_group=None):
process_taric_xml_stream(
xml,
workbasket_id=None,
workbasket_status=workflow_status,
partition_scheme=get_partition_scheme(),
username=valid_user.username,
record_group=record_group,
)
return run_import
@pytest.fixture
def export_xml(valid_user_api_client):
return partial(export_workbasket, valid_user_api_client=valid_user_api_client)
@pytest.fixture
def run_xml_import(import_xml, settings):
"""
Returns a function for checking a model can be imported correctly.
The function takes the following parameters:
model: A model instance, or a factory class used to build the model.
This model should not already exist in the database.
serializer: An optional serializer class to convert the model to its TARIC XML
representation. If not provided, the function attempts to use a serializer
class named after the model, eg measures.serializers.<model-class-name>Serializer
record_group: A taric record group, which can be used to trigger
specific importer behaviour, e.g. for handling commodity code changes
The function serializes the model to TARIC XML, inputs this to the importer, then
fetches the newly created model from the database and compares the fields.
It returns the imported object if there are no discrepancies, allowing it to be
further tested.
"""
def check(
factory: Callable[[], TrackedModel],
serializer: Type[TrackedModelSerializer],
record_group: Sequence[str] = None,
workflow_status: WorkflowStatus = WorkflowStatus.PUBLISHED,
) -> TrackedModel:
get_nursery().cache.clear()
settings.SKIP_WORKBASKET_VALIDATION = True
model = factory()
model_class = type(model)
assert isinstance(
model,
TrackedModel,
), "A factory that returns an object instance needs to be provided"
xml = generate_test_import_xml(
[serializer(model, context={"format": "xml"}).data],
)
import_xml(xml, workflow_status, record_group)
db_kwargs = model.get_identifying_fields()
workbasket = WorkBasket.objects.last()
assert workbasket is not None
try:
imported = model_class.objects.approved_up_to_transaction(
workbasket.current_transaction,
).get(**db_kwargs)
except model_class.DoesNotExist:
if model.update_type == UpdateType.DELETE:
imported = (
model_class.objects.versions_up_to(workbasket.current_transaction)
.filter(**db_kwargs)
.last()
)
else:
raise
assert_records_match(model, imported)
return imported
return check
@pytest.fixture(
params=[v for v in UpdateType],
ids=[v.name for v in UpdateType],
)
def update_type(request):
return request.param
@pytest.fixture
def imported_fields_match(run_xml_import, update_type):
"""
Returns a function that serializes a model to TARIC XML, inputs this to the
importer, then fetches the newly created model from the database and
compares the fields. This is much the same functionality as `run_xml_import`
but with some adjustments for updates and deletes.
A dict of dependencies can also be injected which will be added to the model
when it is built. For any of the values that are factories, they will be
built into real models and saved before the import is carried out.
In addition to `run_xml_import` a previous version of the object is
generated when testing updates or deletes as these can only occur after a
create. The data around version groups is also tested.
"""
def check(
factory: Type[DjangoModelFactory],
serializer: Type[TrackedModelSerializer],
dependencies: Optional[Dict[str, Any]] = None,
):
Model: Type[TrackedModel] = factory._meta.model
previous_version: TrackedModel = None
# Build kwargs and dependencies needed to make a complete model. This
# can't rely on the factory itself as the dependencies need to be in the
# database before the import else they will also appear in the XML.
kwargs = {}
for name, dependency_model in (dependencies or {}).items():