Debian Codegraph @

testing/mozbase/mozlog/tests/test_logtypes.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 # You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import unittest
6
7 import mozunit
8 from mozlog.logtypes import Any, Dict, Int, List, TestList, Tuple, Unicode
9
10
11 class TestContainerTypes(unittest.TestCase):
12 def test_dict_type_basic(self):
13 d = Dict("name")
14 with self.assertRaises(ValueError):
15 d({"foo": "bar"})
16
17 d = Dict(Any, "name")
18 d({"foo": "bar"}) # doesn't raise
19
20 def test_dict_type_with_dictionary_item_type(self):
21 d = Dict({Int: Int}, "name")
22 with self.assertRaises(ValueError):
23 d({"foo": 1})
24
25 with self.assertRaises(ValueError):
26 d({1: "foo"})
27
28 d({1: 2}) # doesn't raise
29
30 def test_dict_type_with_recursive_item_types(self):
31 d = Dict(Dict({Unicode: List(Int)}), "name")
32 with self.assertRaises(ValueError):
33 d({"foo": "bar"})
34
35 with self.assertRaises(ValueError):
36 d({"foo": {"bar": "baz"}})
37
38 with self.assertRaises(ValueError):
39 d({"foo": {"bar": ["baz"]}})
40
41 d({"foo": {"bar": [1]}}) # doesn't raise
42
43 def test_list_type_basic(self):
44 l = List("name")
45 with self.assertRaises(ValueError):
46 l(["foo"])
47
48 l = List(Any, "name")
49 l(["foo", 1]) # doesn't raise
50
51 def test_list_type_with_recursive_item_types(self):
52 l = List(Dict(List(Tuple((Unicode, Int)))), "name")
53 with self.assertRaises(ValueError):
54 l(["foo"])
55
56 with self.assertRaises(ValueError):
57 l([{"foo": "bar"}])
58
59 with self.assertRaises(ValueError):
60 l([{"foo": ["bar"]}])
61
62 l([{"foo": [("bar", 1)]}]) # doesn't raise
63
64 def test_tuple_type_basic(self):
65 t = Tuple("name")
66 with self.assertRaises(ValueError):
67 t((1,))
68
69 t = Tuple(Any, "name")
70 t((1,)) # doesn't raise
71
72 def test_tuple_type_with_tuple_item_type(self):
73 t = Tuple((Unicode, Int))
74 with self.assertRaises(ValueError):
75 t(("foo", "bar"))
76
77 t(("foo", 1)) # doesn't raise
78
79 def test_tuple_type_with_recursive_item_types(self):
80 t = Tuple((Dict(List(Any)), List(Dict(Any)), Unicode), "name")
81 with self.assertRaises(ValueError):
82 t(({"foo": "bar"}, [{"foo": "bar"}], "foo"))
83
84 with self.assertRaises(ValueError):
85 t(({"foo": ["bar"]}, ["foo"], "foo"))
86
87 t(({"foo": ["bar"]}, [{"foo": "bar"}], "foo")) # doesn't raise
88
89
90 class TestDataTypes(unittest.TestCase):
91 def test_test_list(self):
92 t = TestList("name")
93 with self.assertRaises(ValueError):
94 t("foo")
95
96 with self.assertRaises(ValueError):
97 t({"foo": 1})
98
99 d1 = t({"default": ["bar"]}) # doesn't raise
100 d2 = t(["bar"]) # doesn't raise
101
102 self.assertDictContainsSubset(d1, d2)
103
104
105 if __name__ == "__main__":
106 mozunit.main()