test_product_completion.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Guard against cross-SKU contamination and fabricated numeric specifications."""
  2. import hashlib
  3. import importlib.util
  4. import json
  5. from pathlib import Path
  6. import unittest
  7. spec = importlib.util.spec_from_file_location('completion', Path(__file__).with_name('recover-product-completion.py'))
  8. m = importlib.util.module_from_spec(spec)
  9. spec.loader.exec_module(m)
  10. class ExactSkuAttributes(unittest.TestCase):
  11. def page(self, *, selected='123', variants=None, suffix=';', props=None):
  12. item = {'skuId': selected, 'saleProp': props or {'1': '规格'},
  13. 'skuName': '不要把标题 100g*5 当已核重量',
  14. 'newColorSize': variants if variants is not None else [
  15. {'skuId': '999', '1': '其他口味100袋'}, {'skuId': '123', '1': '当前口味五连包'}]}
  16. return ('window._itemOnly = ' + json.dumps({'item': item}, ensure_ascii=False) + suffix).encode()
  17. def parse(self, raw):
  18. return m.select_spec(raw, '123', hashlib.sha256(raw).hexdigest())
  19. def test_only_selected_variant_and_no_title_weights(self):
  20. actual = self.parse(self.page())
  21. self.assertEqual(actual['specText'], '规格:当前口味五连包')
  22. self.assertEqual(actual['attributes'][0]['valuePointer'], '/item/newColorSize/1/1')
  23. self.assertNotIn('netWeightG', actual)
  24. self.assertNotIn('其他', actual['specText'])
  25. def test_wrong_product_rejected(self):
  26. with self.assertRaisesRegex(ValueError, 'PAGE_PRODUCT_MISMATCH'):
  27. self.parse(self.page(selected='999'))
  28. def test_missing_selected_variant_rejected(self):
  29. with self.assertRaisesRegex(ValueError, 'SELECTED_SKU_NOT_UNIQUE'):
  30. self.parse(self.page(variants=[{'skuId': '999', '1': '其他口味'}]))
  31. def test_duplicate_selected_variant_rejected(self):
  32. with self.assertRaisesRegex(ValueError, 'SELECTED_SKU_NOT_UNIQUE'):
  33. self.parse(self.page(variants=[{'skuId': '123', '1': 'a'}, {'skuId': '123', '1': 'b'}]))
  34. def test_unlabelled_display_color_is_not_attribute(self):
  35. with self.assertRaisesRegex(ValueError, 'NO_EXPLICIT_SELECTED_ATTRIBUTE'):
  36. self.parse(self.page(variants=[{'skuId': '123', 'color': 'unproven display text'}]))
  37. def test_changed_original_rejected(self):
  38. with self.assertRaisesRegex(ValueError, 'PAGE_HASH_MISMATCH'):
  39. m.select_spec(self.page() + b'changed', '123', hashlib.sha256(self.page()).hexdigest())
  40. def test_javascript_expression_never_executed_or_accepted(self):
  41. with self.assertRaisesRegex(ValueError, 'NON_LITERAL_ASSIGNMENT'):
  42. self.parse(self.page(suffix='+ maliciousCall();'))
  43. if __name__ == '__main__':
  44. unittest.main()