PageRenderTime 27ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/utils_test.py

https://code.google.com/
Python | 321 lines | 197 code | 73 blank | 51 comment | 17 complexity | a554d150c719900731a9189425f10a29 MD5 | raw file
Possible License(s): Apache-2.0
  1. #!/usr/bin/env python
  2. # Copyright 2010 Google Inc.
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Tests for utility classes."""
  15. import os
  16. import time
  17. from grr.client import conf
  18. from grr.lib import test_lib
  19. from grr.lib import utils
  20. from grr.proto import jobs_pb2
  21. class StoreTests(test_lib.GRRBaseTest):
  22. """Store tests."""
  23. def test01StoreExpiration(self):
  24. """Testing store removes objects when full."""
  25. s = utils.FastStore(max_size=5)
  26. keys = []
  27. for i in range(0, 100):
  28. keys.append(s.Put(i, i))
  29. # This should not raise
  30. s.Get(keys[-1])
  31. # This should raise though
  32. self.assertRaises(KeyError, s.Get, keys[0])
  33. def test02StoreRefresh(self):
  34. """Test that store keeps recently gotten objects fresh."""
  35. s = utils.FastStore(max_size=5)
  36. keys = []
  37. for i in range(0, 5):
  38. keys.append(s.Put(i, i))
  39. # This should not raise because keys[0] should be refreshed each time its
  40. # gotten
  41. for i in range(0, 1000):
  42. s.Get(keys[0])
  43. s.Put(i, i)
  44. def test03Expire(self):
  45. """Tests the expire mechanism."""
  46. s = utils.FastStore(max_size=100)
  47. key = "test1"
  48. s.Put(key, 1)
  49. # This should not raise
  50. self.assertEqual(s.Get(key), 1)
  51. s.ExpireObject(key)
  52. self.assertRaises(KeyError, s.Get, key)
  53. def test04CallBack(self):
  54. """Test that callbacks are called using object destruction."""
  55. results = []
  56. def Callback(obj):
  57. results.append(obj)
  58. s = utils.FastStore(max_size=5, kill_cb=Callback)
  59. for i in range(0, 10):
  60. s.Put(i, i)
  61. # Only the first 5 messages have been expired (and hence called)
  62. self.assertEqual(results, range(0, 5))
  63. def test05TimeBasedCache(self):
  64. original_time = time.time
  65. # Mock the time.time function
  66. time.time = lambda: 100
  67. key = "key"
  68. tested_cache = utils.TimeBasedCache(max_age=50)
  69. # Stop the housekeeper thread - we test it explicitely here
  70. tested_cache.exit = True
  71. tested_cache.Put(key, "hello")
  72. self.assertEqual(tested_cache.Get(key), "hello")
  73. # Fast forward time
  74. time.time = lambda: 160
  75. # Force the housekeeper to run
  76. tested_cache.house_keeper_thread.target()
  77. # This should now be expired
  78. self.assertRaises(KeyError, tested_cache.Get, key)
  79. # Fix up the mock
  80. time.time = original_time
  81. class ProtoDictTests(test_lib.GRRBaseTest):
  82. """ProtoDict tests."""
  83. def setUp(self):
  84. self.proto = jobs_pb2.Dict()
  85. self.dict_test = {}
  86. for i in range(10):
  87. self.dict_test[unicode(i)] = unicode(i)
  88. i = jobs_pb2.DataBlob(string=unicode(i))
  89. self.proto.dat.add(k=i, v=i)
  90. for i in range(10):
  91. self.dict_test[i] = i
  92. i = jobs_pb2.DataBlob(integer=i)
  93. self.proto.dat.add(k=i, v=i)
  94. for i in range(10):
  95. self.dict_test[str(i)] = str(i)
  96. i = jobs_pb2.DataBlob(string=str(i))
  97. self.proto.dat.add(k=i, v=i)
  98. for i in range(10):
  99. test_pb = jobs_pb2.Interface(mac_address="AA:BB:CC:DD:EE:FF")
  100. self.dict_test["p" + str(i)] = test_pb
  101. v = jobs_pb2.DataBlob(data=test_pb.SerializeToString(),
  102. proto_name="Interface")
  103. k = jobs_pb2.DataBlob(string="p" + str(i))
  104. self.proto.dat.add(k=k, v=v)
  105. for i in range(10):
  106. self.dict_test["none" + str(i)] = None
  107. v = jobs_pb2.DataBlob(none="None")
  108. k = jobs_pb2.DataBlob(string="none" + str(i))
  109. self.proto.dat.add(k=k, v=v)
  110. for i in range(10):
  111. self.dict_test["bool" + str(i)] = True
  112. v = jobs_pb2.DataBlob(boolean=True)
  113. k = jobs_pb2.DataBlob(string="bool" + str(i))
  114. self.proto.dat.add(k=k, v=v)
  115. for i in range(10):
  116. self.dict_test["list" + str(i)] = ["c", 1, "u"]
  117. v = jobs_pb2.DataBlob(
  118. list=jobs_pb2.BlobArray(
  119. content=[jobs_pb2.DataBlob(string="c"),
  120. jobs_pb2.DataBlob(integer=1),
  121. jobs_pb2.DataBlob(string="u")
  122. ])
  123. )
  124. k = jobs_pb2.DataBlob(string="list" + str(i))
  125. self.proto.dat.add(k=k, v=v)
  126. def test01ParsingNone(self):
  127. """Testing initializing from None."""
  128. protodict = utils.ProtoDict(None)
  129. self.assertEqual(type(protodict._proto), jobs_pb2.Dict)
  130. self.assertEqual(protodict.ToDict(), {})
  131. def test02InitializingFromProto(self):
  132. """Test initializing from protobuf."""
  133. # Initialize from proto
  134. proto_under_test = utils.ProtoDict(self.proto)
  135. self.assertEqual(proto_under_test.ToDict(), self.dict_test)
  136. def test03InitializingFromDict(self):
  137. """Test initializing from dict."""
  138. # Initialize from dict
  139. proto_under_test = utils.ProtoDict(self.dict_test)
  140. self.assertEqual(proto_under_test.ToDict(), self.dict_test)
  141. def test04InitializingFromString(self):
  142. """Test initializing from string."""
  143. # Initialize from dict
  144. string = self.proto.SerializeToString()
  145. proto_under_test = utils.ProtoDict(string)
  146. self.assertEqual(proto_under_test.ToDict(), self.dict_test)
  147. self.assertEqual(proto_under_test.ToProto().SerializeToString(), string)
  148. def test05Serializing(self):
  149. """Test initializing from dict."""
  150. # Initialize from dict
  151. proto_under_test = utils.ProtoDict(self.proto)
  152. self.assertEqual(proto_under_test.ToDict(), self.dict_test)
  153. self.assertEqual(str(proto_under_test), self.proto.SerializeToString())
  154. def test06GetItem(self):
  155. """Test __getitem__."""
  156. proto_under_test = utils.ProtoDict(self.dict_test)
  157. for k in self.dict_test:
  158. self.assertEqual(proto_under_test[k], self.dict_test[k])
  159. def test07SetItem(self):
  160. """Test __setitem__."""
  161. proto_under_test = utils.ProtoDict()
  162. for k in self.dict_test:
  163. proto_under_test[k] = self.dict_test[k]
  164. self.assertEqual(proto_under_test.ToDict(), self.dict_test)
  165. def test08MultiAssign(self):
  166. """Test we can assign multiple times to the same proto dict."""
  167. proto_under_test = utils.ProtoDict(self.dict_test)
  168. proto_under_test[1] = 1
  169. proto_under_test[1] = 1
  170. self.assertEqual(proto_under_test[1], 1)
  171. def test09Delete(self):
  172. proto_under_test = utils.ProtoDict(dict(a="value1", b="value2"))
  173. self.assertEqual(proto_under_test["a"], "value1")
  174. self.assertEqual(proto_under_test["b"], "value2")
  175. del proto_under_test["a"]
  176. self.assertRaises(KeyError, proto_under_test.__getitem__, "a")
  177. self.assertEqual(proto_under_test.Get("a", "default"), "default")
  178. self.assertEqual(proto_under_test["b"], "value2")
  179. def test10AssignNone(self):
  180. """Test None assignment via dict and directly."""
  181. self.dict_test["none1"] = None
  182. proto_under_test = utils.ProtoDict(self.dict_test)
  183. self.assertEqual(proto_under_test["none1"], None)
  184. proto_under_test["none2"] = None
  185. self.assertEqual(proto_under_test["none2"], None)
  186. def test10AssignBool(self):
  187. """Test boolean assignment via dict and directly."""
  188. self.dict_test["bool1"] = True
  189. self.dict_test["bool2"] = False
  190. proto_under_test = utils.ProtoDict(self.dict_test)
  191. self.assertEqual(proto_under_test["bool1"], True)
  192. self.assertEqual(proto_under_test["bool2"], False)
  193. proto_under_test["bool3"] = True
  194. proto_under_test["bool4"] = False
  195. self.assertEqual(proto_under_test["bool3"], True)
  196. self.assertEqual(proto_under_test["bool4"], False)
  197. def test11ProtoDictIterator(self):
  198. proto_under_test = utils.ProtoDict(self.dict_test)
  199. for key in self.dict_test:
  200. self.assertTrue(key in proto_under_test)
  201. for key in proto_under_test:
  202. self.assertTrue(key in self.dict_test)
  203. self.assertFalse("nonexistent" in proto_under_test)
  204. def test12AssignList(self):
  205. proto_under_test = utils.ProtoDict(self.dict_test)
  206. self.assertEqual(proto_under_test["list1"], ["c", 1, "u"])
  207. class UtilsTest(test_lib.GRRBaseTest):
  208. """Utilities tests."""
  209. def testNormpath(self):
  210. """Test our Normpath."""
  211. data = [
  212. ("foo/../../../../", "/"),
  213. ("/foo/../../../../bar", "/bar"),
  214. ("/foo/bar/../3sdfdfsa/.", "/foo/3sdfdfsa"),
  215. ("../foo/bar", "/foo/bar"),
  216. ("./foo/bar", "/foo/bar"),
  217. ("/", "/"),
  218. ]
  219. for test, expected in data:
  220. self.assertEqual(expected, utils.NormalizePath(test))
  221. class PathSpectTests(test_lib.GRRBaseTest):
  222. """Test the pathspec manipulation function."""
  223. def testPathSpec(self):
  224. """Test that recursive pathspecs are properly parsed."""
  225. path = os.path.join(self.base_path, "test_img.dd")
  226. path2 = "Test Directory/numbers.txt"
  227. p2 = jobs_pb2.Path(path=path2,
  228. pathtype=jobs_pb2.Path.TSK)
  229. p1 = jobs_pb2.Path(path=path,
  230. pathtype=jobs_pb2.Path.OS,
  231. nested_path=p2)
  232. pathspec = utils.Pathspec(p1)
  233. self.assertEqual(pathspec.elements[0].path, path)
  234. self.assertEqual(pathspec.elements[0].HasField("nested_path"), False)
  235. self.assertEqual(pathspec.elements[1].path, path2)
  236. self.assertEqual(pathspec.elements[1].HasField("nested_path"), False)
  237. # Now combine it back to a recursive proto.
  238. self.assertEqual(p1.SerializeToString(),
  239. pathspec.ToProto().SerializeToString())
  240. def testDirname(self):
  241. pathspec = utils.Pathspec(path="/foo").Append(path="/")
  242. self.assertEqual(pathspec.Dirname().CollapsePath(), "/")
  243. pathspec.Append(path="sdasda")
  244. self.assertEqual(pathspec.Dirname().CollapsePath(), "/foo")
  245. def main(argv):
  246. test_lib.main(argv)
  247. if __name__ == "__main__":
  248. conf.StartMain(main)