hash_ut.pyx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # cython: c_string_type=str, c_string_encoding=utf8
  2. from util.generic.hash cimport THashMap
  3. from util.generic.string cimport TString
  4. import pytest
  5. import unittest
  6. from libcpp.pair cimport pair
  7. from cython.operator cimport dereference as deref
  8. def _check_convert(THashMap[TString, int] x):
  9. return x
  10. class TestHash(unittest.TestCase):
  11. def test_constructors_and_assignments(self):
  12. cdef THashMap[TString, int] c1
  13. c1["one"] = 1
  14. c1["two"] = 2
  15. cdef THashMap[TString, int] c2 = THashMap[TString, int](c1)
  16. self.assertEqual(2, c1.size())
  17. self.assertEqual(2, c2.size())
  18. self.assertEqual(1, c1.at("one"))
  19. self.assertTrue(c1.contains("two"))
  20. self.assertTrue(c2.contains("one"))
  21. self.assertEqual(2, c2.at("two"))
  22. c2["three"] = 3
  23. c1 = c2
  24. self.assertEqual(3, c1.size())
  25. self.assertEqual(3, c2.size())
  26. self.assertEqual(3, c1.at("three"))
  27. def test_equality_operator(self):
  28. cdef THashMap[TString, int] base
  29. base["one"] = 1
  30. base["two"] = 2
  31. cdef THashMap[TString, int] c1 = THashMap[TString, int](base)
  32. self.assertTrue(c1==base)
  33. cdef THashMap[TString, int] c2
  34. c2["one"] = 1
  35. c2["two"] = 2
  36. self.assertTrue(c2 == base)
  37. c2["three"] = 3
  38. self.assertTrue(c2 != base)
  39. cdef THashMap[TString, int] c3 = THashMap[TString, int](base)
  40. c3["one"] = 0
  41. self.assertTrue(c3 != base)
  42. def test_insert_erase(self):
  43. cdef THashMap[TString, int] tmp
  44. self.assertTrue(tmp.insert(pair[TString, int]("one", 0)).second)
  45. self.assertFalse(tmp.insert(pair[TString, int]("one", 1)).second)
  46. self.assertTrue(tmp.insert(pair[TString, int]("two", 2)).second)
  47. cdef TString one = "one"
  48. cdef TString two = "two"
  49. self.assertEqual(tmp.erase(one), 1)
  50. self.assertEqual(tmp.erase(two), 1)
  51. self.assertEqual(tmp.size(), 0)
  52. self.assertTrue(tmp.empty())
  53. def test_iterators_and_find(self):
  54. cdef THashMap[TString, int] tmp
  55. self.assertTrue(tmp.begin() == tmp.end())
  56. self.assertTrue(tmp.find("1") == tmp.end())
  57. tmp["1"] = 1
  58. self.assertTrue(tmp.begin() != tmp.end())
  59. cdef THashMap[TString, int].iterator it = tmp.find("1")
  60. self.assertTrue(it != tmp.end())
  61. self.assertEqual(deref(it).second, 1)
  62. def test_convert(self):
  63. src = {'foo': 1, 'bar': 42}
  64. self.assertEqual(_check_convert(src), src)
  65. bad_src = {'foo': 1, 'bar': 'baz'}
  66. with self.assertRaises(TypeError):
  67. _check_convert(bad_src)