forked from inventree/InvenTree
-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_api.py
3209 lines (2516 loc) · 96.9 KB
/
test_api.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
"""Unit tests for the various part API endpoints"""
import os
from datetime import datetime
from decimal import Decimal
from enum import IntEnum
from random import randint
from django.core.exceptions import ValidationError
from django.db import connection
from django.test.utils import CaptureQueriesContext
from django.urls import reverse
import PIL
from rest_framework import status
from rest_framework.test import APIClient
import build.models
import company.models
import order.models
from common.models import InvenTreeSetting
from company.models import Company, SupplierPart
from InvenTree.status_codes import (BuildStatus, PurchaseOrderStatusGroups,
StockStatus)
from InvenTree.unit_test import InvenTreeAPITestCase
from part.models import (BomItem, BomItemSubstitute, Part, PartCategory,
PartCategoryParameterTemplate, PartParameter,
PartParameterTemplate, PartRelated, PartStocktake,
PartTestTemplate)
from stock.models import StockItem, StockLocation
class PartCategoryAPITest(InvenTreeAPITestCase):
"""Unit tests for the PartCategory API."""
fixtures = [
'category',
'part',
'params',
'location',
'bom',
'company',
'test_templates',
'manufacturer_part',
'supplier_part',
'order',
'stock',
]
roles = [
'part.change',
'part.add',
'part.delete',
'part_category.change',
'part_category.add',
'part_category.delete',
]
def test_category_list(self):
"""Test the PartCategoryList API endpoint"""
url = reverse('api-part-category-list')
# star categories manually for tests as it is not possible with fixures
# because the current user is no fixure itself and throws an invalid
# foreign key constrain
for pk in [3, 4]:
PartCategory.objects.get(pk=pk).set_starred(self.user, True)
test_cases = [
({}, 8, 'no parameters'),
({'parent': 1, 'cascade': False}, 3, 'Filter by parent, no cascading'),
({'parent': 1, 'cascade': True}, 5, 'Filter by parent, cascading'),
({'cascade': True, 'depth': 0}, 8, 'Cascade with no parent, depth=0'),
({'cascade': False, 'depth': 10}, 8, 'Cascade with no parent, depth=0'),
({'parent': 'null', 'cascade': True, 'depth': 0}, 2, 'Cascade with null parent, depth=0'),
({'parent': 'null', 'cascade': True, 'depth': 10}, 8, 'Cascade with null parent and bigger depth'),
({'parent': 'null', 'cascade': False, 'depth': 10}, 2, 'No cascade even with depth specified with null parent'),
({'parent': 1, 'cascade': False, 'depth': 0}, 3, 'Dont cascade with depth=0 and parent'),
({'parent': 1, 'cascade': True, 'depth': 0}, 3, 'Cascade with depth=0 and parent'),
({'parent': 1, 'cascade': False, 'depth': 1}, 3, 'Dont cascade even with depth=1 specified with parent'),
({'parent': 1, 'cascade': True, 'depth': 1}, 5, 'Cascade with depth=1 with parent'),
({'parent': 1, 'cascade': True, 'depth': 'abcdefg'}, 5, 'Cascade with invalid depth and parent'),
({'parent': 42}, 8, 'Should return everything if parent_pk is not valid'),
({'parent': 'null', 'exclude_tree': 1, 'cascade': True}, 2, 'Should return everything from except tree with pk=1'),
({'parent': 'null', 'exclude_tree': 42, 'cascade': True}, 8, 'Should return everything because exclude_tree=42 is no valid pk'),
({'parent': 1, 'starred': True, 'cascade': True}, 2, 'Should return the starred categories for the current user within the pk=1 tree'),
({'parent': 1, 'starred': False, 'cascade': True}, 3, 'Should return the not starred categories for the current user within the pk=1 tree'),
]
for params, res_len, description in test_cases:
response = self.get(url, params, expected_code=200)
self.assertEqual(len(response.data), res_len, description)
# Check that the required fields are present
fields = [
'pk',
'name',
'description',
'default_location',
'level',
'parent',
'part_count',
'pathstring',
'url'
]
response = self.get(url, expected_code=200)
for result in response.data:
for f in fields:
self.assertIn(f, result, f'"{f}" is missing in result of PartCategory list')
def test_part_count(self):
"""Test that the 'part_count' field is annotated correctly"""
url = reverse('api-part-category-list')
# Create a parent category
cat = PartCategory.objects.create(
name='Parent Cat',
description='Some name',
parent=None
)
# Create child categories
for ii in range(10):
child = PartCategory.objects.create(
name=f"Child cat {ii}",
description="A child category",
parent=cat
)
# Create parts in this category
for jj in range(10):
Part.objects.create(
name=f"Part xyz {jj}_{ii}",
description="A test part with a description",
category=child
)
# Filter by parent category
response = self.get(
url,
{
'parent': cat.pk,
},
expected_code=200
)
# 10 child categories
self.assertEqual(len(response.data), 10)
for result in response.data:
self.assertEqual(result['parent'], cat.pk)
self.assertEqual(result['part_count'], 10)
# Detail view for parent category
response = self.get(
f'/api/part/category/{cat.pk}/',
expected_code=200
)
# Annotation should include parts from all sub-categories
self.assertEqual(response.data['part_count'], 100)
def test_category_parameters(self):
"""Test that the PartCategoryParameterTemplate API function work"""
url = reverse('api-part-category-parameter-list')
response = self.get(url, {}, expected_code=200)
self.assertEqual(len(response.data), 2)
# Add some more category templates via the API
n = PartParameterTemplate.objects.count()
for template in PartParameterTemplate.objects.all():
response = self.post(
url,
{
'category': 2,
'parameter_template': template.pk,
'default_value': 'xyz',
}
)
# Total number of category templates should have increased
response = self.get(url, {}, expected_code=200)
self.assertEqual(len(response.data), 2 + n)
# Filter by category
response = self.get(
url,
{
'category': 2,
}
)
self.assertEqual(len(response.data), n)
# Test that we can retrieve individual templates via the API
for template in PartCategoryParameterTemplate.objects.all():
url = reverse('api-part-category-parameter-detail', kwargs={'pk': template.pk})
data = self.get(url, {}, expected_code=200).data
for key in ['pk', 'category', 'category_detail', 'parameter_template', 'parameter_template_detail', 'default_value']:
self.assertIn(key, data.keys())
# Test that we can delete via the API also
response = self.delete(url, expected_code=204)
# There should not be any templates left at this point
self.assertEqual(PartCategoryParameterTemplate.objects.count(), 0)
def test_bleach(self):
"""Test that the data cleaning functionality is working.
This helps to protect against XSS injection
"""
url = reverse('api-part-category-detail', kwargs={'pk': 1})
# Invalid values containing tags
invalid_values = [
'<img src="test"/>',
'<a href="#">Link</a>',
"<a href='#'>Link</a>",
'<b>',
]
for v in invalid_values:
response = self.patch(
url,
{
'description': v
},
expected_code=400
)
self.assertIn('Remove HTML tags', str(response.data))
# Raw characters should be allowed
allowed = [
'<< hello',
'Alpha & Omega',
'A > B > C',
]
for val in allowed:
response = self.patch(
url,
{
'description': val,
},
expected_code=200,
)
self.assertEqual(response.data['description'], val)
def test_invisible_chars(self):
"""Test that invisible characters are removed from the input data"""
url = reverse('api-part-category-detail', kwargs={'pk': 1})
values = [
'A part\n category\n\t',
'A\t part\t category\t',
'A pa\rrt cat\r\r\regory',
'A part\u200e catego\u200fry\u202e'
]
for val in values:
response = self.patch(
url,
{
'description': val,
},
expected_code=200,
)
self.assertEqual(response.data['description'], 'A part category')
def test_category_delete(self):
"""Test category deletion with different parameters"""
class Target(IntEnum):
move_subcategories_to_parent_move_parts_to_parent = 0,
move_subcategories_to_parent_delete_parts = 1,
delete_subcategories_move_parts_to_parent = 2,
delete_subcategories_delete_parts = 3,
for i in range(4):
delete_child_categories: bool = False
delete_parts: bool = False
if i in (Target.move_subcategories_to_parent_delete_parts, Target.delete_subcategories_delete_parts):
delete_parts = True
if i in (Target.delete_subcategories_move_parts_to_parent, Target.delete_subcategories_delete_parts):
delete_child_categories = True
# Create a parent category
parent_category = PartCategory.objects.create(
name='Parent category',
description='This is the parent category where the child categories and parts are moved to',
parent=None
)
category_count_before = PartCategory.objects.count()
part_count_before = Part.objects.count()
# Create a category to delete
cat_to_delete = PartCategory.objects.create(
name='Category to delete',
description='This is the category to be deleted',
parent=parent_category
)
url = reverse('api-part-category-detail', kwargs={'pk': cat_to_delete.id})
parts = []
# Create parts in the category to be deleted
for jj in range(3):
parts.append(Part.objects.create(
name=f"Part xyz {i}_{jj}",
description="Child part of the deleted category",
category=cat_to_delete
))
child_categories = []
child_categories_parts = []
# Create child categories under the category to be deleted
for ii in range(3):
child = PartCategory.objects.create(
name=f"Child parent_cat {i}_{ii}",
description="A child category of the deleted category",
parent=cat_to_delete
)
child_categories.append(child)
# Create parts in the child categories
for jj in range(3):
child_categories_parts.append(Part.objects.create(
name=f"Part xyz {i}_{jj}_{ii}",
description="Child part in the child category of the deleted category",
category=child
))
# Delete the created category (sub categories and their parts will be moved under the parent)
params = {}
if delete_parts:
params['delete_parts'] = '1'
if delete_child_categories:
params['delete_child_categories'] = '1'
response = self.delete(
url,
params,
expected_code=204,
)
self.assertEqual(response.status_code, 204)
if delete_parts:
if i == Target.delete_subcategories_delete_parts:
# Check if all parts deleted
self.assertEqual(Part.objects.count(), part_count_before)
elif i == Target.move_subcategories_to_parent_delete_parts:
# Check if all parts deleted
self.assertEqual(Part.objects.count(), part_count_before + len(child_categories_parts))
else:
# parts moved to the parent category
for part in parts:
part.refresh_from_db()
self.assertEqual(part.category, parent_category)
if delete_child_categories:
for part in child_categories_parts:
part.refresh_from_db()
self.assertEqual(part.category, parent_category)
if delete_child_categories:
# Check if all categories are deleted
self.assertEqual(PartCategory.objects.count(), category_count_before)
else:
# Check if all subcategories to parent moved to parent and all parts deleted
for child in child_categories:
child.refresh_from_db()
self.assertEqual(child.parent, parent_category)
def test_structural(self):
"""Test the effectiveness of structural categories
Make sure:
- Parts cannot be created in structural categories
- Parts cannot be assigned to structural categories
"""
# Create our structural part category
structural_category = PartCategory.objects.create(
name='Structural category',
description='This is the structural category',
parent=None,
structural=True
)
part_count_before = Part.objects.count()
# Make sure that we get an error if we try to create part in the structural category
with self.assertRaises(ValidationError):
part = Part.objects.create(
name="-",
description="Part which shall not be created",
category=structural_category
)
# Ensure that the part really did not get created in the structural category
self.assertEqual(part_count_before, Part.objects.count())
# Create a non structural category for test part category change
non_structural_category = PartCategory.objects.create(
name='Non-structural category',
description='This is a non-structural category',
parent=None,
structural=False
)
# Create the test part assigned to a non-structural category
part = Part.objects.create(
name="-",
description="Part which category will be changed to structural",
category=non_structural_category
)
# Assign the test part to a structural category and make sure it gives an error
part.category = structural_category
with self.assertRaises(ValidationError):
part.save()
# Ensure that the part did not get saved to the DB
part.refresh_from_db()
self.assertEqual(part.category.pk, non_structural_category.pk)
def test_path_detail(self):
"""Test path_detail information"""
url = reverse('api-part-category-detail', kwargs={'pk': 5})
# First, request without path detail
response = self.get(
url,
{
'path_detail': False,
},
expected_code=200
)
# Check that the path detail information is not included
self.assertFalse('path' in response.data.keys())
# Now, request *with* path detail
response = self.get(
url,
{
'path_detail': True,
},
expected_code=200
)
self.assertTrue('path' in response.data.keys())
path = response.data['path']
self.assertEqual(len(path), 3)
self.assertEqual(path[0]['name'], 'Electronics')
self.assertEqual(path[1]['name'], 'IC')
self.assertEqual(path[2]['name'], 'MCU')
class PartOptionsAPITest(InvenTreeAPITestCase):
"""Tests for the various OPTIONS endpoints in the /part/ API.
Ensure that the required field details are provided!
"""
roles = [
'part.add',
]
def test_part(self):
"""Test the Part API OPTIONS."""
actions = self.getActions(reverse('api-part-list'))['POST']
# Check that a bunch o' fields are contained
for f in ['assembly', 'component', 'description', 'image', 'IPN']:
self.assertTrue(f in actions.keys())
# Active is a 'boolean' field
active = actions['active']
self.assertTrue(active['default'])
self.assertEqual(active['help_text'], 'Is this part active?')
self.assertEqual(active['type'], 'boolean')
self.assertEqual(active['read_only'], False)
# String field
ipn = actions['IPN']
self.assertEqual(ipn['type'], 'string')
self.assertFalse(ipn['required'])
self.assertEqual(ipn['max_length'], 100)
self.assertEqual(ipn['help_text'], 'Internal Part Number')
# Related field
category = actions['category']
self.assertEqual(category['type'], 'related field')
self.assertTrue(category['required'])
self.assertFalse(category['read_only'])
self.assertEqual(category['label'], 'Category')
self.assertEqual(category['model'], 'partcategory')
self.assertEqual(category['api_url'], reverse('api-part-category-list'))
self.assertEqual(category['help_text'], 'Part category')
def test_category(self):
"""Test the PartCategory API OPTIONS endpoint."""
actions = self.getActions(reverse('api-part-category-list'))
# actions should *not* contain 'POST' as we do not have the correct role
self.assertFalse('POST' in actions)
self.assignRole('part_category.add')
actions = self.getActions(reverse('api-part-category-list'))['POST']
name = actions['name']
self.assertTrue(name['required'])
self.assertEqual(name['label'], 'Name')
loc = actions['default_location']
self.assertEqual(loc['api_url'], reverse('api-location-list'))
def test_bom_item(self):
"""Test the BomItem API OPTIONS endpoint."""
actions = self.getActions(reverse('api-bom-list'))['POST']
inherited = actions['inherited']
self.assertEqual(inherited['type'], 'boolean')
# 'part' reference
part = actions['part']
self.assertTrue(part['required'])
self.assertFalse(part['read_only'])
self.assertTrue(part['filters']['assembly'])
# 'sub_part' reference
sub_part = actions['sub_part']
self.assertTrue(sub_part['required'])
self.assertEqual(sub_part['type'], 'related field')
self.assertTrue(sub_part['filters']['component'])
class PartAPITestBase(InvenTreeAPITestCase):
"""Base class for running tests on the Part API endpoints"""
fixtures = [
'category',
'part',
'location',
'bom',
'build',
'company',
'test_templates',
'manufacturer_part',
'params',
'supplier_part',
'order',
'stock',
]
roles = [
'part.change',
'part.add',
'part.delete',
'part_category.change',
'part_category.add',
]
class PartAPITest(PartAPITestBase):
"""Series of tests for the Part DRF API."""
fixtures = [
'category',
'part',
'location',
'bom',
'company',
'test_templates',
'manufacturer_part',
'params',
'supplier_part',
'order',
]
def test_get_categories(self):
"""Test that we can retrieve list of part categories, with various filtering options."""
url = reverse('api-part-category-list')
# Request *all* part categories
response = self.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 8)
# Request top-level part categories only
response = self.get(
url,
{
'parent': 'null',
}
)
self.assertEqual(len(response.data), 2)
# Children of PartCategory<1>, cascade
response = self.get(
url,
{
'parent': 1,
'cascade': 'true',
}
)
self.assertEqual(len(response.data), 5)
# Children of PartCategory<1>, do not cascade
response = self.get(
url,
{
'parent': 1,
'cascade': 'false',
}
)
self.assertEqual(len(response.data), 3)
def test_add_categories(self):
"""Check that we can add categories."""
data = {
'name': 'Animals',
'description': 'All animals go here'
}
url = reverse('api-part-category-list')
response = self.post(url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
parent = response.data['pk']
# Add some sub-categories to the top-level 'Animals' category
for animal in ['cat', 'dog', 'zebra']:
data = {
'name': animal,
'description': 'A sort of animal',
'parent': parent,
}
response = self.post(url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['parent'], parent)
self.assertEqual(response.data['name'], animal)
self.assertEqual(response.data['pathstring'], 'Animals/' + animal)
# There should be now 8 categories
response = self.get(url)
self.assertEqual(len(response.data), 12)
def test_cat_detail(self):
"""Test the PartCategoryDetail API endpoint"""
url = reverse('api-part-category-detail', kwargs={'pk': 4})
response = self.get(url)
# Test that we have retrieved the category
self.assertEqual(response.data['description'], 'Integrated Circuits')
self.assertEqual(response.data['parent'], 1)
# Change some data and post it back
data = response.data
data['name'] = 'Changing category'
data['parent'] = None
data['description'] = 'Changing the description'
response = self.patch(url, data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['description'], 'Changing the description')
self.assertIsNone(response.data['parent'])
def test_filter_parts(self):
"""Test part filtering using the API"""
url = reverse('api-part-list')
data = {'cascade': True}
response = self.get(url, data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), Part.objects.count())
# Test filtering parts by category
data = {'category': 2}
response = self.get(url, data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
# There should only be 2 objects in category C
self.assertEqual(len(response.data), 2)
for part in response.data:
self.assertEqual(part['category'], 2)
def test_filter_by_in_bom(self):
"""Test that we can filter part list by the 'in_bom_for' parameter"""
url = reverse('api-part-list')
response = self.get(
url,
{
'in_bom_for': 100,
},
expected_code=200,
)
self.assertEqual(len(response.data), 4)
def test_filter_by_related(self):
"""Test that we can filter by the 'related' status"""
url = reverse('api-part-list')
# Initially there are no relations, so this should return zero results
response = self.get(url, {'related': 1}, expected_code=200)
self.assertEqual(len(response.data), 0)
# Add some relationships
PartRelated.objects.create(
part_1=Part.objects.get(pk=1),
part_2=Part.objects.get(pk=2),
)
PartRelated.objects.create(
part_2=Part.objects.get(pk=1),
part_1=Part.objects.get(pk=3)
)
response = self.get(url, {'related': 1}, expected_code=200)
self.assertEqual(len(response.data), 2)
def test_filter_by_convert(self):
"""Test that we can correctly filter the Part list by conversion options"""
category = PartCategory.objects.get(pk=3)
# First, construct a set of template / variant parts
master_part = Part.objects.create(
name='Master', description='Master part which has some variants',
category=category,
is_template=True,
)
# Construct a set of variant parts
variants = []
for color in ['Red', 'Green', 'Blue', 'Yellow', 'Pink', 'Black']:
variants.append(Part.objects.create(
name=f"{color} Variant", description="Variant part with a specific color",
variant_of=master_part,
category=category,
))
url = reverse('api-part-list')
# An invalid part ID will return an error
response = self.get(
url,
{
'convert_from': 999999,
},
expected_code=400
)
self.assertIn('Select a valid choice', str(response.data['convert_from']))
for variant in variants:
response = self.get(
url,
{
'convert_from': variant.pk,
},
expected_code=200,
)
# There should be the same number of results for each request
self.assertEqual(len(response.data), 6)
id_values = [p['pk'] for p in response.data]
self.assertIn(master_part.pk, id_values)
for v in variants:
# Check that all *other* variants are included also
if v == variant:
continue
self.assertIn(v.pk, id_values)
def test_include_children(self):
"""Test the special 'include_child_categories' flag.
If provided, parts are provided for ANY child category (recursive)
"""
url = reverse('api-part-list')
data = {'category': 1, 'cascade': True}
# Now request to include child categories
response = self.get(url, data)
# Now there should be 5 total parts
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 3)
def test_test_templates(self):
"""Test the PartTestTemplate API"""
url = reverse('api-part-test-template-list')
# List ALL items
response = self.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 7)
# Request for a particular part
response = self.get(url, data={'part': 10000})
self.assertEqual(len(response.data), 5)
response = self.get(url, data={'part': 10004})
self.assertEqual(len(response.data), 7)
# Try to post a new object (missing description)
response = self.post(
url,
data={
'part': 10000,
'test_name': 'My very first test',
'required': False,
}
)
self.assertEqual(response.status_code, 400)
# Try to post a new object (should succeed)
response = self.post(
url,
data={
'part': 10000,
'test_name': 'New Test',
'required': True,
'description': 'a test description'
}
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Try to post a new test with the same name (should fail)
response = self.post(
url,
data={
'part': 10004,
'test_name': " newtest",
'description': 'dafsdf',
}
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
# Try to post a new test against a non-trackable part (should fail)
response = self.post(
url,
data={
'part': 1,
'test_name': 'A simple test',
}
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_get_thumbs(self):
"""Return list of part thumbnails."""
url = reverse('api-part-thumbs')
response = self.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_paginate(self):
"""Test pagination of the Part list API."""
for n in [1, 5, 10]:
response = self.get(reverse('api-part-list'), {'limit': n})
data = response.data
self.assertIn('count', data)
self.assertIn('results', data)
self.assertEqual(len(data['results']), n)
def test_template_filters(self):
"""Unit tests for API filters related to template parts:
- variant_of : Return children of specified part
- ancestor : Return descendants of specified part
Uses the 'chair template' part (pk=10000)
"""
# Rebuild the MPTT structure before running these tests
Part.objects.rebuild()
url = reverse('api-part-list')
response = self.get(
url,
{
'variant_of': 10000,
},
expected_code=200
)
# 3 direct children of template part
self.assertEqual(len(response.data), 3)
response = self.get(
url,
{
'ancestor': 10000,
},
expected_code=200,
)
# 4 total descendants
self.assertEqual(len(response.data), 4)
# Use the 'green chair' as our reference
response = self.get(
url,
{
'variant_of': 10003,
},
expected_code=200,
)
self.assertEqual(len(response.data), 1)
response = self.get(
url,
{
'ancestor': 10003,
},
expected_code=200,
)
self.assertEqual(len(response.data), 1)
# Add some more variants
p = Part.objects.get(pk=10004)
for i in range(100):
Part.objects.create(
name=f'Chair variant {i}',
description='A new chair variant',
variant_of=p,
)
# There should still be only one direct variant
response = self.get(
url,
{
'variant_of': 10003,
},
expected_code=200,
)
self.assertEqual(len(response.data), 1)
# However, now should be 101 descendants
response = self.get(
url,
{
'ancestor': 10003,
},
expected_code=200,
)
self.assertEqual(len(response.data), 101)
def test_variant_stock(self):
"""Unit tests for the 'variant_stock' annotation, which provides a stock count for *variant* parts."""
# Ensure the MPTT structure is in a known state before running tests
Part.objects.rebuild()
# Initially, there are no "chairs" in stock,