/
tests.py
1501 lines (1152 loc) · 51.2 KB
/
tests.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
"""Test general functions and helpers."""
import json
import os
import time
from datetime import datetime, timedelta
from decimal import Decimal
from unittest import mock
import django.core.exceptions as django_exceptions
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core import mail
from django.core.exceptions import ValidationError
from django.test import TestCase, override_settings, tag
from django.urls import reverse
import pint.errors
from djmoney.contrib.exchange.exceptions import MissingRate
from djmoney.contrib.exchange.models import Rate, convert_money
from djmoney.money import Money
from maintenance_mode.core import get_maintenance_mode, set_maintenance_mode
from sesame.utils import get_user
import InvenTree.conversion
import InvenTree.format
import InvenTree.helpers
import InvenTree.helpers_model
import InvenTree.tasks
from common.models import CustomUnit, InvenTreeSetting
from common.settings import currency_codes
from InvenTree.helpers_mixin import ClassProviderMixin, ClassValidationMixin
from InvenTree.sanitizer import sanitize_svg
from InvenTree.unit_test import InvenTreeTestCase
from part.models import Part, PartCategory
from stock.models import StockItem, StockLocation
from . import config, helpers, ready, status, version
from .tasks import offload_task
from .validators import validate_overage
class ConversionTest(TestCase):
"""Tests for conversion of physical units."""
def test_prefixes(self):
"""Test inputs where prefixes are used."""
tests = {
'3': 3,
'3m': 3,
'3mm': 0.003,
'3k': 3000,
'3u': 0.000003,
'3 inch': 0.0762,
}
for val, expected in tests.items():
q = InvenTree.conversion.convert_physical_value(val, 'm')
self.assertAlmostEqual(q, expected, 3)
def test_engineering_units(self):
"""Test that conversion works with engineering notation."""
# Run some basic checks over the helper function
tests = [
('3', '3'),
('3k3', '3.3k'),
('123R45', '123.45R'),
('10n5F', '10.5nF'),
]
for val, expected in tests:
self.assertEqual(
InvenTree.conversion.from_engineering_notation(val), expected
)
# Now test the conversion function
tests = [('33k3ohm', 33300), ('123kohm45', 123450), ('10n005', 0.000000010005)]
for val, expected in tests:
output = InvenTree.conversion.convert_physical_value(
val, 'ohm', strip_units=True
)
self.assertAlmostEqual(output, expected, 12)
def test_scientific_notation(self):
"""Test that scientific notation is handled correctly."""
tests = [
('3E2', 300),
('-12.3E-3', -0.0123),
('1.23E-3', 0.00123),
('99E9', 99000000000),
]
for val, expected in tests:
output = InvenTree.conversion.convert_physical_value(val, strip_units=True)
self.assertAlmostEqual(output, expected, 6)
def test_temperature_units(self):
"""Test conversion of temperature units.
Ref: https://github.com/inventree/InvenTree/issues/6495
"""
tests = [
('3.3°F', '°C', -15.944),
('273°K', '°F', 31.73),
('900', '°C', 900),
('900°F', 'degF', 900),
('900°K', '°C', 626.85),
('800', 'kelvin', 800),
('-100°C', 'fahrenheit', -148),
('-100 °C', 'Fahrenheit', -148),
('-100 Celsius', 'fahrenheit', -148),
('-123.45 fahrenheit', 'kelvin', 186.7888),
('-99Fahrenheit', 'Celsius', -72.7777),
]
for val, unit, expected in tests:
output = InvenTree.conversion.convert_physical_value(
val, unit, strip_units=True
)
self.assertAlmostEqual(output, expected, 3)
def test_base_units(self):
"""Test conversion to specified base units."""
tests = {
'3': 3,
'3 dozen': 36,
'50 dozen kW': 600000,
'1 / 10': 0.1,
'1/2 kW': 500,
'1/2 dozen kW': 6000,
'0.005 MW': 5000,
}
for val, expected in tests.items():
q = InvenTree.conversion.convert_physical_value(val, 'W')
self.assertAlmostEqual(q, expected, places=2)
q = InvenTree.conversion.convert_physical_value(val, 'W', strip_units=False)
self.assertAlmostEqual(float(q.magnitude), expected, places=2)
def test_dimensionless_units(self):
"""Tests for 'dimensionless' unit quantities."""
# Test some dimensionless units
tests = {
'ea': 1,
'each': 1,
'3 piece': 3,
'5 dozen': 60,
'3 hundred': 300,
'2 thousand': 2000,
'12 pieces': 12,
'1 / 10': 0.1,
'1/2': 0.5,
'-1 / 16': -0.0625,
'3/2': 1.5,
'1/2 dozen': 6,
}
for val, expected in tests.items():
# Convert, and leave units
q = InvenTree.conversion.convert_physical_value(val, strip_units=False)
self.assertAlmostEqual(float(q.magnitude), expected, 3)
# Convert, and strip units
q = InvenTree.conversion.convert_physical_value(val)
self.assertAlmostEqual(q, expected, 3)
def test_invalid_units(self):
"""Test conversion with bad units."""
tests = {'3': '10', '13': '-?-', '-3': 'xyz', '-12': '-12', '1/0': '1/0'}
for val, unit in tests.items():
with self.assertRaises(ValidationError):
InvenTree.conversion.convert_physical_value(val, unit)
def test_invalid_values(self):
"""Test conversion of invalid inputs."""
inputs = ['-x', '1/0', 'xyz', '12B45C']
for val in inputs:
# Test with a provided unit
with self.assertRaises(ValidationError):
InvenTree.conversion.convert_physical_value(val, 'meter')
# Test dimensionless
with self.assertRaises(ValidationError):
InvenTree.conversion.convert_physical_value(val)
def test_custom_units(self):
"""Tests for custom unit conversion."""
# Start with an empty set of units
CustomUnit.objects.all().delete()
InvenTree.conversion.reload_unit_registry()
# Ensure that the custom unit does *not* exist to start with
reg = InvenTree.conversion.get_unit_registry()
with self.assertRaises(pint.errors.UndefinedUnitError):
reg['hpmm']
# Create a new custom unit
CustomUnit.objects.create(
name='fanciful_unit', definition='henry / mm', symbol='hpmm'
)
# Reload registry
reg = InvenTree.conversion.get_unit_registry()
# Ensure that the custom unit is now available
reg['hpmm']
# Convert some values
tests = {
'1': 1,
'1 hpmm': 1000000,
'1 / 10 hpmm': 100000,
'1 / 100 hpmm': 10000,
'0.3 hpmm': 300000,
'-7hpmm': -7000000,
}
for val, expected in tests.items():
# Convert, and leave units
q = InvenTree.conversion.convert_physical_value(
val, 'henry / km', strip_units=False
)
self.assertAlmostEqual(float(q.magnitude), expected, 2)
# Convert and strip units
q = InvenTree.conversion.convert_physical_value(val, 'henry / km')
self.assertAlmostEqual(q, expected, 2)
class ValidatorTest(TestCase):
"""Simple tests for custom field validators."""
def test_overage(self):
"""Test overage validator."""
validate_overage('100%')
validate_overage('10')
validate_overage('45.2 %')
with self.assertRaises(django_exceptions.ValidationError):
validate_overage('-1')
with self.assertRaises(django_exceptions.ValidationError):
validate_overage('-2.04 %')
with self.assertRaises(django_exceptions.ValidationError):
validate_overage('105%')
with self.assertRaises(django_exceptions.ValidationError):
validate_overage('xxx %')
with self.assertRaises(django_exceptions.ValidationError):
validate_overage('aaaa')
def test_url_validation(self):
"""Test for AllowedURLValidator."""
from common.models import InvenTreeSetting
from part.models import Part, PartCategory
# Without strict URL validation
InvenTreeSetting.set_setting('INVENTREE_STRICT_URLS', False, None)
n = Part.objects.count()
cat = PartCategory.objects.first()
# Should pass, even without a schema
Part.objects.create(
name=f'Part {n}',
description='Link without schema',
category=cat,
link='www.google.com',
)
# With strict URL validation
InvenTreeSetting.set_setting('INVENTREE_STRICT_URLS', True, None)
with self.assertRaises(ValidationError):
Part.objects.create(
name=f'Part {n + 1}',
description='Link without schema',
category=cat,
link='www.google.com',
)
class FormatTest(TestCase):
"""Unit tests for custom string formatting functionality."""
def test_parse(self):
"""Tests for the 'parse_format_string' function."""
# Extract data from a valid format string
fmt = 'PO-{abc:02f}-{ref:04d}-{date}-???'
info = InvenTree.format.parse_format_string(fmt)
self.assertIn('abc', info)
self.assertIn('ref', info)
self.assertIn('date', info)
# Try with invalid strings
for fmt in ['PO-{{xyz}', 'PO-{xyz}}', 'PO-{xyz}-{']:
with self.assertRaises(ValueError):
InvenTree.format.parse_format_string(fmt)
def test_create_regex(self):
"""Test function for creating a regex from a format string."""
tests = {
'PO-123-{ref:04f}': r'^PO\-123\-(?P<ref>.+)$',
'{PO}-???-{ref}-{date}-22': r'^(?P<PO>.+)\-...\-(?P<ref>.+)\-(?P<date>.+)\-22$',
'ABC-123-###-{ref}': r'^ABC\-123\-\d\d\d\-(?P<ref>.+)$',
'ABC-123': r'^ABC\-123$',
}
for fmt, reg in tests.items():
self.assertEqual(InvenTree.format.construct_format_regex(fmt), reg)
def test_validate_format(self):
"""Test that string validation works as expected."""
# These tests should pass
for value, pattern in {
'ABC-hello-123': '???-{q}-###',
'BO-1234': 'BO-{ref}',
'111.222.fred.china': '???.###.{name}.{place}',
'PO-1234': 'PO-{ref:04d}',
}.items():
self.assertTrue(InvenTree.format.validate_string(value, pattern))
# These tests should fail
for value, pattern in {
'ABC-hello-123': '###-{q}-???',
'BO-1234': 'BO.{ref}',
'BO-####': 'BO-{pattern}-{next}',
'BO-123d': 'BO-{ref:04d}',
}.items():
self.assertFalse(InvenTree.format.validate_string(value, pattern))
def test_extract_value(self):
"""Test that we can extract named values based on a format string."""
# Simple tests based on a straight-forward format string
fmt = 'PO-###-{ref:04d}'
tests = {'123': 'PO-123-123', '456': 'PO-123-456', '789': 'PO-123-789'}
for k, v in tests.items():
self.assertEqual(InvenTree.format.extract_named_group('ref', v, fmt), k)
# However these ones should fail
tests = {'abc': 'PO-123-abc', 'xyz': 'PO-123-xyz'}
for v in tests.values():
with self.assertRaises(ValueError):
InvenTree.format.extract_named_group('ref', v, fmt)
# More complex tests
fmt = 'PO-{date}-{test}-???-{ref}-###'
val = 'PO-2022-02-01-hello-ABC-12345-222'
data = {'date': '2022-02-01', 'test': 'hello', 'ref': '12345'}
for k, v in data.items():
self.assertEqual(InvenTree.format.extract_named_group(k, val, fmt), v)
# Test for error conditions
# Raises a ValueError as the format string is bad
with self.assertRaises(ValueError):
InvenTree.format.extract_named_group('test', 'PO-1234-5', 'PO-{test}-{')
# Raises a NameError as the named group does not exist in the format string
with self.assertRaises(NameError):
InvenTree.format.extract_named_group('missing', 'PO-12345', 'PO-{test}')
# Raises a ValueError as the value does not match the format string
with self.assertRaises(ValueError):
InvenTree.format.extract_named_group('test', 'PO-1234', 'PO-{test}-1234')
with self.assertRaises(ValueError):
InvenTree.format.extract_named_group('test', 'PO-ABC-xyz', 'PO-###-{test}')
def test_currency_formatting(self):
"""Test that currency formatting works correctly for multiple currencies."""
test_data = (
(Money(3651.285718, 'USD'), 4, True, '$3,651.2857'), # noqa: E201,E202
(Money(487587.849178, 'CAD'), 5, True, 'CA$487,587.84918'), # noqa: E201,E202
(Money(0.348102, 'EUR'), 1, False, '0.3'), # noqa: E201,E202
(Money(0.916530, 'GBP'), 1, True, '£0.9'), # noqa: E201,E202
(Money(61.031024, 'JPY'), 3, False, '61.031'), # noqa: E201,E202
(Money(49609.694602, 'JPY'), 1, True, '¥49,609.7'), # noqa: E201,E202
(Money(155565.264777, 'AUD'), 2, False, '155,565.26'), # noqa: E201,E202
(Money(0.820437, 'CNY'), 4, True, 'CN¥0.8204'), # noqa: E201,E202
(Money(7587.849178, 'EUR'), 0, True, '€7,588'), # noqa: E201,E202
(Money(0.348102, 'GBP'), 3, False, '0.348'), # noqa: E201,E202
(Money(0.652923, 'CHF'), 0, True, 'CHF1'), # noqa: E201,E202
(Money(0.820437, 'CNY'), 1, True, 'CN¥0.8'), # noqa: E201,E202
(Money(98789.5295680, 'CHF'), 0, False, '98,790'), # noqa: E201,E202
(Money(0.585787, 'USD'), 1, True, '$0.6'), # noqa: E201,E202
(Money(0.690541, 'CAD'), 3, True, 'CA$0.691'), # noqa: E201,E202
(Money(427.814104, 'AUD'), 5, True, 'A$427.81410'), # noqa: E201,E202
)
with self.settings(LANGUAGE_CODE='en-us'):
for value, decimal_places, include_symbol, expected_result in test_data:
result = InvenTree.format.format_money(
value, decimal_places=decimal_places, include_symbol=include_symbol
)
self.assertEqual(result, expected_result)
class TestHelpers(TestCase):
"""Tests for InvenTree helper functions."""
def test_absolute_url(self):
"""Test helper function for generating an absolute URL."""
base = 'https://demo.inventree.org:12345'
InvenTreeSetting.set_setting('INVENTREE_BASE_URL', base, change_user=None)
tests = {
'': base,
'api/': base + '/api/',
'/api/': base + '/api/',
'api': base + '/api',
'media/label/output/': base + '/media/label/output/',
'static/logo.png': base + '/static/logo.png',
'https://www.google.com': 'https://www.google.com',
'https://demo.inventree.org:12345/out.html': 'https://demo.inventree.org:12345/out.html',
'https://demo.inventree.org/test.html': 'https://demo.inventree.org/test.html',
'http://www.cwi.nl:80/%7Eguido/Python.html': 'http://www.cwi.nl:80/%7Eguido/Python.html',
'test.org': base + '/test.org',
}
for url, expected in tests.items():
# Test with supplied base URL
self.assertEqual(
InvenTree.helpers_model.construct_absolute_url(url, base_url=base),
expected,
)
# Test without supplied base URL
self.assertEqual(
InvenTree.helpers_model.construct_absolute_url(url), expected
)
def test_image_url(self):
"""Test if a filename looks like an image."""
for name in ['ape.png', 'bat.GiF', 'apple.WeBP', 'BiTMap.Bmp']:
self.assertTrue(helpers.TestIfImageURL(name))
for name in ['no.doc', 'nah.pdf', 'whatpng']:
self.assertFalse(helpers.TestIfImageURL(name))
def test_str2bool(self):
"""Test string to boolean conversion."""
for s in ['yes', 'Y', 'ok', '1', 'OK', 'Ok', 'tRuE', 'oN']:
self.assertTrue(helpers.str2bool(s))
self.assertFalse(helpers.str2bool(s, test=False))
for s in ['nO', '0', 'none', 'noNE', None, False, 'falSe', 'off']:
self.assertFalse(helpers.str2bool(s))
self.assertTrue(helpers.str2bool(s, test=False))
for s in ['wombat', '', 'xxxx']:
self.assertFalse(helpers.str2bool(s))
self.assertFalse(helpers.str2bool(s, test=False))
def test_isnull(self):
"""Test isNull."""
for s in ['null', 'none', '', '-1', 'false']:
self.assertTrue(helpers.isNull(s))
for s in ['yes', 'frog', 'llama', 'true']:
self.assertFalse(helpers.isNull(s))
def testStaticUrl(self):
"""Test static url helpers."""
self.assertEqual(helpers.getStaticUrl('test.jpg'), '/static/test.jpg')
self.assertEqual(helpers.getBlankImage(), '/static/img/blank_image.png')
self.assertEqual(
helpers.getBlankThumbnail(), '/static/img/blank_image.thumbnail.png'
)
def testMediaUrl(self):
"""Test getMediaUrl."""
self.assertEqual(helpers.getMediaUrl('xx/yy.png'), '/media/xx/yy.png')
def testDecimal2String(self):
"""Test decimal2string."""
self.assertEqual(helpers.decimal2string(Decimal('1.2345000')), '1.2345')
self.assertEqual(helpers.decimal2string('test'), 'test')
def test_logo_image(self):
"""Test for retrieving logo image."""
# By default, there is no custom logo provided
logo = helpers.getLogoImage()
self.assertEqual(logo, '/static/img/inventree.png')
logo = helpers.getLogoImage(as_file=True)
self.assertEqual(logo, f'file://{settings.STATIC_ROOT}/img/inventree.png')
def test_download_image(self):
"""Test function for downloading image from remote URL."""
# Run check with a sequence of bad URLs
for url in ['blog', 'htp://test.com/?', 'google', '\\invalid-url']:
with self.assertRaises(django_exceptions.ValidationError):
InvenTree.helpers_model.download_image_from_url(url)
def dl_helper(url, expected_error, timeout=2.5, retries=3):
"""Helper function for unit testing downloads.
As the httpstat.us service occasionally refuses a connection,
we will simply try multiple times
"""
tries = 0
with self.assertRaises(expected_error):
while tries < retries:
try:
InvenTree.helpers_model.download_image_from_url(
url, timeout=timeout
)
break
except Exception as exc:
if type(exc) is expected_error:
# Re-throw this error
raise exc
else:
print('Unexpected error:', type(exc), exc)
tries += 1
time.sleep(10 * tries)
# Attempt to download an image which throws a 404
# TODO: Re-implement this test when we are happier with the external service
# dl_helper("https://httpstat.us/404", requests.exceptions.HTTPError, timeout=10)
# Attempt to download, but timeout
# TODO: Re-implement this test when we are happier with the external service
# dl_helper("https://httpstat.us/200?sleep=5000", requests.exceptions.ReadTimeout, timeout=1)
large_img = 'https://github.com/inventree/InvenTree/raw/0.14.x/InvenTree/InvenTree/static/img/paper_splash_large.jpg'
InvenTreeSetting.set_setting(
'INVENTREE_DOWNLOAD_IMAGE_MAX_SIZE', 1, change_user=None
)
# Attempt to download an image which is too large
with self.assertRaises(ValueError):
InvenTree.helpers_model.download_image_from_url(large_img, timeout=10)
# Increase allowable download size
InvenTreeSetting.set_setting(
'INVENTREE_DOWNLOAD_IMAGE_MAX_SIZE', 5, change_user=None
)
# Download a valid image (should not throw an error)
InvenTree.helpers_model.download_image_from_url(large_img, timeout=10)
def test_model_mixin(self):
"""Test the getModelsWithMixin function."""
from InvenTree.models import InvenTreeBarcodeMixin
models = InvenTree.helpers_model.getModelsWithMixin(InvenTreeBarcodeMixin)
self.assertIn(Part, models)
self.assertIn(StockLocation, models)
self.assertIn(StockItem, models)
self.assertNotIn(PartCategory, models)
self.assertNotIn(InvenTreeSetting, models)
def test_test_key(self):
"""Test for the generateTestKey function."""
tests = {
' Hello World ': 'helloworld',
' MY NEW TEST KEY ': 'mynewtestkey',
' 1234 5678': '_12345678',
' 100 percenT': '_100percent',
' MY_NEW_TEST': 'my_new_test',
' 100_new_tests': '_100_new_tests',
}
for name, key in tests.items():
self.assertEqual(helpers.generateTestKey(name), key)
class TestQuoteWrap(TestCase):
"""Tests for string wrapping."""
def test_single(self):
"""Test WrapWithQuotes."""
self.assertEqual(helpers.WrapWithQuotes('hello'), '"hello"')
self.assertEqual(helpers.WrapWithQuotes('hello"'), '"hello"')
class TestIncrement(TestCase):
"""Tests for increment function."""
def tests(self):
"""Test 'intelligent' incrementing function."""
tests = [
('', '1'),
(1, '2'),
('001', '002'),
('1001', '1002'),
('ABC123', 'ABC124'),
('XYZ0', 'XYZ1'),
('123Q', '123Q'),
('QQQ', 'QQQ'),
]
for test in tests:
a, b = test
result = helpers.increment(a)
self.assertEqual(result, b)
class TestMakeBarcode(TestCase):
"""Tests for barcode string creation."""
def test_barcode_extended(self):
"""Test creation of barcode with extended data."""
bc = helpers.MakeBarcode(
'part', 3, {'id': 3, 'url': 'www.google.com'}, brief=False
)
self.assertIn('part', bc)
self.assertIn('tool', bc)
self.assertIn('"tool": "InvenTree"', bc)
data = json.loads(bc)
self.assertEqual(data['part']['id'], 3)
self.assertEqual(data['part']['url'], 'www.google.com')
def test_barcode_brief(self):
"""Test creation of simple barcode."""
bc = helpers.MakeBarcode('stockitem', 7)
data = json.loads(bc)
self.assertEqual(len(data), 1)
self.assertEqual(data['stockitem'], 7)
class TestDownloadFile(TestCase):
"""Tests for DownloadFile."""
def test_download(self):
"""Tests for DownloadFile."""
helpers.DownloadFile('hello world', 'out.txt')
helpers.DownloadFile(bytes(b'hello world'), 'out.bin')
class TestMPTT(TestCase):
"""Tests for the MPTT tree models."""
fixtures = ['location']
@classmethod
def setUpTestData(cls):
"""Setup for all tests."""
super().setUpTestData()
StockLocation.objects.rebuild()
def test_self_as_parent(self):
"""Test that we cannot set self as parent."""
loc = StockLocation.objects.get(pk=4)
loc.parent = loc
with self.assertRaises(ValidationError):
loc.save()
def test_child_as_parent(self):
"""Test that we cannot set a child as parent."""
parent = StockLocation.objects.get(pk=4)
child = StockLocation.objects.get(pk=5)
parent.parent = child
with self.assertRaises(ValidationError):
parent.save()
def test_move(self):
"""Move an item to a different tree."""
drawer = StockLocation.objects.get(name='Drawer_1')
# Record the tree ID
tree = drawer.tree_id
home = StockLocation.objects.get(name='Home')
drawer.parent = home
drawer.save()
self.assertNotEqual(tree, drawer.tree_id)
class TestSerialNumberExtraction(TestCase):
"""Tests for serial number extraction code.
Note that while serial number extraction is made available to custom plugins,
only simple integer-based extraction is tested here.
"""
def test_simple(self):
"""Test simple serial numbers."""
e = helpers.extract_serial_numbers
# Test a range of numbers
sn = e('1-5', 5, 1)
self.assertEqual(len(sn), 5)
for i in range(1, 6):
self.assertIn(str(i), sn)
sn = e('11-30', 20, 1)
self.assertEqual(len(sn), 20)
sn = e('1, 2, 3, 4, 5', 5, 1)
self.assertEqual(len(sn), 5)
# Test partially specifying serials
sn = e('1, 2, 4+', 5, 1)
self.assertEqual(len(sn), 5)
self.assertEqual(sn, ['1', '2', '4', '5', '6'])
# Test groups are not interpolated if enough serials are supplied
sn = e('1, 2, 3, AF5-69H, 5', 5, 1)
self.assertEqual(len(sn), 5)
self.assertEqual(sn, ['1', '2', '3', 'AF5-69H', '5'])
# Test groups are not interpolated with more than one hyphen in a word
sn = e('1, 2, TG-4SR-92, 4+', 5, 1)
self.assertEqual(len(sn), 5)
self.assertEqual(sn, ['1', '2', 'TG-4SR-92', '4', '5'])
# Test multiple placeholders
sn = e('1 2 ~ ~ ~', 5, 2)
self.assertEqual(len(sn), 5)
self.assertEqual(sn, ['1', '2', '3', '4', '5'])
sn = e('1-5, 10-15', 11, 1)
self.assertIn('3', sn)
self.assertIn('13', sn)
sn = e('1+', 10, 1)
self.assertEqual(len(sn), 10)
self.assertEqual(sn, [str(_) for _ in range(1, 11)])
sn = e('4, 1+2', 4, 1)
self.assertEqual(len(sn), 4)
self.assertEqual(sn, ['4', '1', '2', '3'])
sn = e('~', 1, 1)
self.assertEqual(len(sn), 1)
self.assertEqual(sn, ['2'])
sn = e('~', 1, 3)
self.assertEqual(len(sn), 1)
self.assertEqual(sn, ['4'])
sn = e('~+', 2, 4)
self.assertEqual(len(sn), 2)
self.assertEqual(sn, ['5', '6'])
sn = e('~+3', 4, 4)
self.assertEqual(len(sn), 4)
self.assertEqual(sn, ['5', '6', '7', '8'])
def test_failures(self):
"""Test wrong serial numbers."""
e = helpers.extract_serial_numbers
# Test duplicates
with self.assertRaises(ValidationError):
e('1,2,3,3,3', 5, 1)
# Test invalid length
with self.assertRaises(ValidationError):
e('1,2,3', 5, 1)
# Test empty string
with self.assertRaises(ValidationError):
e(', , ,', 0, 1)
# Test incorrect sign in group
with self.assertRaises(ValidationError):
e('10-2', 8, 1)
# Test invalid group
with self.assertRaises(ValidationError):
e('1-5-10', 10, 1)
with self.assertRaises(ValidationError):
e('10, a, 7-70j', 4, 1)
# Test groups are not interpolated with word characters
with self.assertRaises(ValidationError):
e('1, 2, 3, E-5', 5, 1)
# Extract a range of values with a smaller range
with self.assertRaises(ValidationError) as exc:
e('11-50', 10, 1)
self.assertIn('Range quantity exceeds 10', str(exc))
# Test groups are not interpolated with alpha characters
with self.assertRaises(ValidationError) as exc:
e('1, A-2, 3+', 5, 1)
self.assertIn('Invalid group range: A-2', str(exc))
def test_combinations(self):
"""Test complex serial number combinations."""
e = helpers.extract_serial_numbers
sn = e('1 3-5 9+2', 7, 1)
self.assertEqual(len(sn), 7)
self.assertEqual(sn, ['1', '3', '4', '5', '9', '10', '11'])
sn = e('1,3-5,9+2', 7, 1)
self.assertEqual(len(sn), 7)
self.assertEqual(sn, ['1', '3', '4', '5', '9', '10', '11'])
sn = e('~+2', 3, 13)
self.assertEqual(len(sn), 3)
self.assertEqual(sn, ['14', '15', '16'])
sn = e('~+', 2, 13)
self.assertEqual(len(sn), 2)
self.assertEqual(sn, ['14', '15'])
# Test multiple increment groups
sn = e('~+4, 20+4, 30+4', 15, 10)
self.assertEqual(len(sn), 15)
for v in [14, 24, 34]:
self.assertIn(str(v), sn)
# Test multiple range groups
sn = e('11-20, 41-50, 91-100', 30, 1)
self.assertEqual(len(sn), 30)
for v in range(11, 21):
self.assertIn(str(v), sn)
for v in range(41, 51):
self.assertIn(str(v), sn)
for v in range(91, 101):
self.assertIn(str(v), sn)
class TestVersionNumber(TestCase):
"""Unit tests for version number functions."""
def test_tuple(self):
"""Test inventreeVersionTuple."""
v = version.inventreeVersionTuple()
self.assertEqual(len(v), 3)
s = '.'.join([str(i) for i in v])
self.assertTrue(s in version.inventreeVersion())
def test_comparison(self):
"""Test direct comparison of version numbers."""
v_a = version.inventreeVersionTuple('1.2.0')
v_b = version.inventreeVersionTuple('1.2.3')
v_c = version.inventreeVersionTuple('1.2.4')
v_d = version.inventreeVersionTuple('2.0.0')
self.assertTrue(v_b > v_a)
self.assertTrue(v_c > v_b)
self.assertTrue(v_d > v_c)
self.assertTrue(v_d > v_a)
def test_commit_info(self):
"""Test that the git commit information is extracted successfully."""
envs = {
'INVENTREE_COMMIT_HASH': 'abcdef',
'INVENTREE_COMMIT_DATE': '2022-12-31',
}
# Check that the environment variables take priority
with mock.patch.dict(os.environ, envs):
self.assertEqual(version.inventreeCommitHash(), 'abcdef')
self.assertEqual(version.inventreeCommitDate(), '2022-12-31')
import subprocess
# Check that the current .git values work too
hash = str(
subprocess.check_output('git rev-parse --short HEAD'.split()), 'utf-8'
).strip()
self.assertEqual(hash, version.inventreeCommitHash())
d = (
str(subprocess.check_output('git show -s --format=%ci'.split()), 'utf-8')
.strip()
.split(' ')[0]
)
self.assertEqual(d, version.inventreeCommitDate())
class CurrencyTests(TestCase):
"""Unit tests for currency / exchange rate functionality."""
def test_rates(self):
"""Test exchange rate update."""
# Initially, there will not be any exchange rate information
rates = Rate.objects.all()
self.assertEqual(rates.count(), 0)
# Without rate information, we cannot convert anything...
with self.assertRaises(MissingRate):
convert_money(Money(100, 'USD'), 'AUD')
with self.assertRaises(MissingRate):
convert_money(Money(100, 'AUD'), 'USD')
update_successful = False
# Note: the update sometimes fails in CI, let's give it a few chances
for _ in range(10):
InvenTree.tasks.update_exchange_rates()
rates = Rate.objects.all()
if rates.count() == len(currency_codes()):
update_successful = True
break
else: # pragma: no cover
print('Exchange rate update failed - retrying')
print(f'Expected {currency_codes()}, got {[a.currency for a in rates]}')
time.sleep(1)
self.assertTrue(update_successful)
# Now that we have some exchange rate information, we can perform conversions
# Forwards
convert_money(Money(100, 'USD'), 'AUD')
# Backwards
convert_money(Money(100, 'AUD'), 'USD')
# Convert between non base currencies
convert_money(Money(100, 'CAD'), 'NZD')
# Convert to a symbol which is not covered
with self.assertRaises(MissingRate):
convert_money(Money(100, 'GBP'), 'ZWL')
class TestStatus(TestCase):
"""Unit tests for status functions."""
def test_check_system_health(self):
"""Test that the system health check is false in testing -> background worker not running."""
self.assertEqual(status.check_system_health(), False)
def test_TestMode(self):
"""Test isInTestMode check."""
self.assertTrue(ready.isInTestMode())
def test_Importing(self):
"""Test isImportingData check."""
self.assertEqual(ready.isImportingData(), False)
class TestSettings(InvenTreeTestCase):
"""Unit tests for settings."""
superuser = True
def in_env_context(self, envs=None):
"""Patch the env to include the given dict."""
# Set default - see B006
if envs is None:
envs = {}
return mock.patch.dict(os.environ, envs)
def run_reload(self, envs=None):
"""Helper function to reload InvenTree."""
# Set default - see B006
if envs is None:
envs = {}
from plugin import registry
with self.in_env_context(envs):
settings.USER_ADDED = False
registry.reload_plugins()
@override_settings(TESTING_ENV=True)