Best Python code snippet using autotest_python
test_archive_python.py
Source:test_archive_python.py
1"""2Testcases for NSArchive-ing python objects.3(Implementation is incomplete)4"""5import os6import sys7import pickle8if sys.version_info[0] == 3:9 import copyreg10else:11 import copy_reg as copyreg12from PyObjCTools.TestSupport import *13import objc._pycoder as pycoder14from PyObjCTest.fnd import NSArchiver, NSUnarchiver15from PyObjCTest.fnd import NSKeyedArchiver, NSKeyedUnarchiver16from PyObjCTest.fnd import NSData, NSArray, NSDictionary17from PyObjCTest.fnd import NSMutableArray, NSMutableDictionary18#19# First set of tests: the stdlib tests for pickling, this20# should test everything but mixed Python/Objective-C21# object-graphs.22#23if sys.version_info[0] == 3:24 unicode = str25 long = int26import test.pickletester27MyList = test.pickletester.MyList28class reduce_global (object):29 def __reduce__(self):30 return "reduce_global"31reduce_global = reduce_global()32# Quick hack to add a proper __repr__ to class C in33# pickletester, makes it a lot easier to debug.34def C__repr__(self):35 return '<%s instance at %#x: %r>'%(36 self.__class__.__name__, id(self), self.__dict__)37test.pickletester.C.__repr__ = C__repr__38del C__repr__39class myobject :40 def __init__(self):41 pass42 def __getinitargs__(self):43 return (1,2)44class state_obj_1:45 def __getstate__(self):46 return ({'a': 1, 42: 3}, {'b': 2})47class mystr(str):48 __slots__ = ()49class myint(int):50 __slots__ = ()51def a_function():52 pass53class a_classic_class:54 pass55class a_classic_class_with_state:56 def __getstate__(self):57 return {'a': 1}58 def __setstate__(self, state):59 for k, v in state.items():60 setattr(self, k, v)61class a_newstyle_class (object):62 pass63class newstyle_with_slots (object):64 __slots__ = ('a', 'b', '__dict__')65class newstyle_with_setstate (object):66 def __setstate__(self, state):67 self.state = state68def make_instance(state):69 o = a_reducing_class()70 o.__dict__.update(state)71 return o72class a_reducing_class (object):73 def __reduce__(self):74 return make_instance, (self.__dict__,)75class TestKeyedArchiveSimple (TestCase):76 def setUp(self):77 self.archiverClass = NSKeyedArchiver78 self.unarchiverClass = NSKeyedUnarchiver79 def test_unknown_type(self):80 try:81 orig = pycoder.decode_dispatch[pycoder.kOP_GLOBAL]82 del pycoder.decode_dispatch[pycoder.kOP_GLOBAL]83 o = TestKeyedArchiveSimple84 buf = self.archiverClass.archivedDataWithRootObject_(o)85 self.assertRaises(pickle.UnpicklingError, self.unarchiverClass.unarchiveObjectWithData_, buf)86 finally:87 pycoder.decode_dispatch[pycoder.kOP_GLOBAL] = orig88 def test_reducing_issues(self):89 class Error1 (object):90 def __reduce__(self):91 return dir, 'foo'92 object1 = Error1()93 self.assertRaises(pickle.PicklingError, self.archiverClass.archivedDataWithRootObject_,94 object1)95 class Error2 (object):96 def __reduce__(self):97 return 'foo', (1, 2)98 object2 = Error2()99 self.assertRaises(pickle.PicklingError, self.archiverClass.archivedDataWithRootObject_,100 object2)101 def test_various_objects(self):102 o = a_newstyle_class()103 o.attr1 = False104 o.attr2 = None105 o.__dict__[42] = 3106 buf = self.archiverClass.archivedDataWithRootObject_(o)107 self.assertIsInstance(buf, NSData)108 v = self.unarchiverClass.unarchiveObjectWithData_(buf)109 self.assertIsInstance(v, a_newstyle_class)110 self.assertEqual(v.__dict__, o.__dict__)111 def test_misc_globals(self):112 global mystr 113 orig = mystr114 try:115 del mystr116 o = orig('hello')117 self.assertRaises(pickle.PicklingError, self.archiverClass.archivedDataWithRootObject_, o)118 finally:119 mystr = orig120 try:121 mystr = None122 o = orig('hello')123 self.assertRaises(pickle.PicklingError, self.archiverClass.archivedDataWithRootObject_, o)124 finally:125 mystr = orig126 try:127 copyreg.add_extension(a_newstyle_class.__module__, a_newstyle_class.__name__, 42)128 self.assertIn((a_newstyle_class.__module__, a_newstyle_class.__name__), copyreg._extension_registry)129 o = a_newstyle_class130 buf = self.archiverClass.archivedDataWithRootObject_(o)131 self.assertIsInstance(buf, NSData)132 v = self.unarchiverClass.unarchiveObjectWithData_(buf)133 self.assertIs(v, o)134 self.assertIsInstance(buf, NSData)135 v = self.unarchiverClass.unarchiveObjectWithData_(buf)136 self.assertIs(v, o)137 copyreg.remove_extension(a_newstyle_class.__module__, a_newstyle_class.__name__, 42)138 self.assertRaises(ValueError, self.unarchiverClass.unarchiveObjectWithData_, buf)139 finally:140 mystr = orig141 try:142 copyreg.remove_extension(a_newstyle_class.__module__, a_newstyle_class.__name__, 42)143 except ValueError:144 pass145 def f(): pass146 del f.__module__147 try:148 sys.f = f149 buf = self.archiverClass.archivedDataWithRootObject_(f)150 self.assertIsInstance(buf, NSData)151 v = self.unarchiverClass.unarchiveObjectWithData_(buf)152 self.assertIs(v, f)153 finally:154 del f155 @onlyPython2156 def test_invalid_initargs(self):157 v = myobject()158 buf = self.archiverClass.archivedDataWithRootObject_(v)159 self.assertIsInstance(buf, NSData)160 self.assertRaises(TypeError, self.unarchiverClass.unarchiveObjectWithData_, buf)161 def test_class_with_slots(self):162 # Test dumpling a class with slots163 o = newstyle_with_slots()164 o.a = 1165 o.b = 2166 o.c = 3167 buf = self.archiverClass.archivedDataWithRootObject_(o)168 self.assertIsInstance(buf, NSData)169 v = self.unarchiverClass.unarchiveObjectWithData_(buf)170 self.assertIsInstance(v, newstyle_with_slots)171 self.assertEqual(v.a, 1)172 self.assertEqual(v.b, 2)173 self.assertEqual(v.c, 3)174 @onlyPython2175 def test_class_with_state(self):176 o = state_obj_1()177 buf = self.archiverClass.archivedDataWithRootObject_(o)178 self.assertIsInstance(buf, NSData)179 v = self.unarchiverClass.unarchiveObjectWithData_(buf)180 self.assertIsInstance(v, state_obj_1)181 self.assertEqual(v.a, 1)182 self.assertEqual(v.b, 2)183 self.assertEqual(v.__dict__[42], 3)184 def test_class_with_setstate(self):185 o = newstyle_with_setstate()186 o.a = 1187 o.b = 2188 buf = self.archiverClass.archivedDataWithRootObject_(o)189 self.assertIsInstance(buf, NSData)190 v = self.unarchiverClass.unarchiveObjectWithData_(buf)191 self.assertIsInstance(v, newstyle_with_setstate)192 self.assertEqual(v.state, {'a': 1, 'b': 2})193 194 def test_reduce_as_global(self):195 # Test class where __reduce__ returns a string (the name of a global)196 o = reduce_global197 buf = self.archiverClass.archivedDataWithRootObject_(o)198 self.assertIsInstance(buf, NSData)199 v = self.unarchiverClass.unarchiveObjectWithData_(buf)200 self.assertIs(v, reduce_global)201 def test_reduce_invalid(self):202 class invalid_reduce (object):203 def __reduce__(self):204 return 42205 self.assertRaises(pickle.PicklingError, self.archiverClass.archivedDataWithRootObject_, invalid_reduce())206 class invalid_reduce (object):207 def __reduce__(self):208 return (1,)209 self.assertRaises(pickle.PicklingError, self.archiverClass.archivedDataWithRootObject_, invalid_reduce())210 class invalid_reduce (object):211 def __reduce__(self):212 return (1,2,3,4,5,6)213 self.assertRaises(pickle.PicklingError, self.archiverClass.archivedDataWithRootObject_, invalid_reduce())214 def test_basic_objects(self):215 buf = self.archiverClass.archivedDataWithRootObject_(a_function)216 self.assertIsInstance(buf, NSData)217 v = self.unarchiverClass.unarchiveObjectWithData_(buf)218 self.assertIs(v, a_function)219 buf = self.archiverClass.archivedDataWithRootObject_(a_classic_class)220 self.assertIsInstance(buf, NSData)221 v = self.unarchiverClass.unarchiveObjectWithData_(buf)222 self.assertIs(v, a_classic_class)223 buf = self.archiverClass.archivedDataWithRootObject_(a_newstyle_class)224 self.assertIsInstance(buf, NSData)225 v = self.unarchiverClass.unarchiveObjectWithData_(buf)226 self.assertIs(v, a_newstyle_class)227 o = a_classic_class()228 o.x = 42229 buf = self.archiverClass.archivedDataWithRootObject_(o)230 self.assertIsInstance(buf, NSData)231 v = self.unarchiverClass.unarchiveObjectWithData_(buf)232 self.assertIsInstance(v, a_classic_class)233 self.assertEqual(v.x, 42)234 o = a_classic_class_with_state()235 buf = self.archiverClass.archivedDataWithRootObject_(o)236 self.assertIsInstance(buf, NSData)237 v = self.unarchiverClass.unarchiveObjectWithData_(buf)238 self.assertIsInstance(v, a_classic_class_with_state)239 self.assertEqual(v.a, 1)240 for o in (None, [None], (None,), {None,}):241 buf = self.archiverClass.archivedDataWithRootObject_(o)242 self.assertIsInstance(buf, NSData)243 v = self.unarchiverClass.unarchiveObjectWithData_(buf)244 self.assertEqual(o, v)245 for o in (True, False, [True]):246 buf = self.archiverClass.archivedDataWithRootObject_(o)247 self.assertIsInstance(buf, NSData)248 v = self.unarchiverClass.unarchiveObjectWithData_(buf)249 self.assertEqual(o, v)250 o = ('aap', 42)251 buf = self.archiverClass.archivedDataWithRootObject_(o)252 self.assertIsInstance(buf, NSData)253 v = self.unarchiverClass.unarchiveObjectWithData_(buf)254 self.assertIsInstance(v, tuple)255 self.assertEqual(o, v)256 o = ['aap', 42]257 buf = self.archiverClass.archivedDataWithRootObject_(o)258 self.assertIsInstance(buf, NSData)259 v = self.unarchiverClass.unarchiveObjectWithData_(buf)260 self.assertIsInstance(v, list)261 self.assertEqual(o, v)262 o = {'aap': 'monkey', 'noot': 'nut' }263 buf = self.archiverClass.archivedDataWithRootObject_(o)264 self.assertIsInstance(buf, NSData)265 v = self.unarchiverClass.unarchiveObjectWithData_(buf)266 self.assertIsInstance(v, dict)267 self.assertEqual(o, v)268 o = {1, 2, 3}269 buf = self.archiverClass.archivedDataWithRootObject_(o)270 self.assertIsInstance(buf, NSData)271 v = self.unarchiverClass.unarchiveObjectWithData_(buf)272 self.assertIsInstance(v, set)273 self.assertEqual(o, v)274 o = 'hello world'275 buf = self.archiverClass.archivedDataWithRootObject_(o)276 self.assertIsInstance(buf, NSData)277 v = self.unarchiverClass.unarchiveObjectWithData_(buf)278 self.assertIsInstance(v, str)279 self.assertEqual(o, v)280 o = b'hello world'281 buf = self.archiverClass.archivedDataWithRootObject_(o)282 self.assertIsInstance(buf, NSData)283 v = self.unarchiverClass.unarchiveObjectWithData_(buf)284 self.assertIsInstance(v, bytes)285 self.assertEqual(o, v)286 o = b'hello world'.decode('ascii')287 buf = self.archiverClass.archivedDataWithRootObject_(o)288 self.assertIsInstance(buf, NSData)289 v = self.unarchiverClass.unarchiveObjectWithData_(buf)290 self.assertIsInstance(v, type(o))291 self.assertEqual(o, v)292 o = mystr('hello world')293 buf = self.archiverClass.archivedDataWithRootObject_(o)294 self.assertIsInstance(buf, NSData)295 v = self.unarchiverClass.unarchiveObjectWithData_(buf)296 self.assertIsInstance(v, mystr)297 self.assertEqual(o, v)298 o = myint(4)299 buf = self.archiverClass.archivedDataWithRootObject_(o)300 self.assertIsInstance(buf, NSData)301 v = self.unarchiverClass.unarchiveObjectWithData_(buf)302 self.assertIsInstance(v, myint)303 self.assertEqual(o, v)304 o = 42.5305 buf = self.archiverClass.archivedDataWithRootObject_(o)306 self.assertIsInstance(buf, NSData)307 v = self.unarchiverClass.unarchiveObjectWithData_(buf)308 self.assertIsInstance(v, float)309 self.assertEqual(o, v)310 if sys.version_info[0] == 2:311 buf = self.archiverClass.archivedDataWithRootObject_(unicode("hello"))312 self.assertIsInstance(buf, NSData)313 v = self.unarchiverClass.unarchiveObjectWithData_(buf)314 self.assertIsInstance(v, unicode)315 buf = self.archiverClass.archivedDataWithRootObject_("hello")316 self.assertIsInstance(buf, NSData)317 v = self.unarchiverClass.unarchiveObjectWithData_(buf)318 self.assertIsInstance(v, str)319 self.assertEqual(v, "hello")320 buf = self.archiverClass.archivedDataWithRootObject_(sys.maxsize * 4)321 self.assertIsInstance(buf, NSData)322 v = self.unarchiverClass.unarchiveObjectWithData_(buf)323 self.assertIsInstance(v, long)324 self.assertEqual(v, sys.maxsize * 4)325 buf = self.archiverClass.archivedDataWithRootObject_(sys.maxsize ** 4)326 self.assertIsInstance(buf, NSData)327 v = self.unarchiverClass.unarchiveObjectWithData_(buf)328 self.assertIsInstance(v, long)329 self.assertEqual(v, sys.maxsize ** 4)330 def testSimpleLists(self):331 o = []332 buf = self.archiverClass.archivedDataWithRootObject_(o)333 self.assertIsInstance(buf, NSData)334 v = self.unarchiverClass.unarchiveObjectWithData_(buf)335 self.assertIsInstance(v, list)336 self.assertEqual(v, o)337 o = [unicode("hello"), 42]338 buf = self.archiverClass.archivedDataWithRootObject_(o)339 self.assertIsInstance(buf, NSData)340 v = self.unarchiverClass.unarchiveObjectWithData_(buf)341 self.assertIsInstance(v, list)342 self.assertEqual(v, o)343 def testSimpleTuples(self):344 o = ()345 buf = self.archiverClass.archivedDataWithRootObject_(o)346 self.assertIsInstance(buf, NSData)347 v = self.unarchiverClass.unarchiveObjectWithData_(buf)348 self.assertIsInstance(v, tuple)349 self.assertEqual(v, o)350 o = (unicode("hello"), 42)351 buf = self.archiverClass.archivedDataWithRootObject_(o)352 self.assertIsInstance(buf, NSData)353 v = self.unarchiverClass.unarchiveObjectWithData_(buf)354 self.assertIsInstance(v, tuple)355 self.assertEqual(v, o)356 def testSimpleDicts(self):357 o = {}358 buf = self.archiverClass.archivedDataWithRootObject_(o)359 self.assertIsInstance(buf, NSData)360 v = self.unarchiverClass.unarchiveObjectWithData_(buf)361 self.assertIsInstance(v, dict)362 self.assertEqual(v, o)363 o = {unicode("hello"): unicode("bar"), 42: 1.5 }364 buf = self.archiverClass.archivedDataWithRootObject_(o)365 self.assertIsInstance(buf, NSData)366 v = self.unarchiverClass.unarchiveObjectWithData_(buf)367 self.assertIsInstance(v, dict)368 self.assertEqual(v, o)369 def testNestedDicts(self):370 o = {371 unicode("hello"): { 1:2 },372 unicode("world"): unicode("foobar")373 }374 buf = self.archiverClass.archivedDataWithRootObject_(o)375 self.assertIsInstance(buf, NSData)376 v = self.unarchiverClass.unarchiveObjectWithData_(buf)377 self.assertIsInstance(v, dict)378 self.assertEqual(v, o)379 o = {}380 o[unicode('self')] = o381 buf = self.archiverClass.archivedDataWithRootObject_(o)382 self.assertIsInstance(buf, NSData)383 v = self.unarchiverClass.unarchiveObjectWithData_(buf)384 self.assertIsInstance(v, dict)385 self.assertIs(v[unicode('self')], v)386 def testNestedSequences(self):387 o = [ 1, 2, 3, (5, (unicode('a'), unicode('b')), 6), {1:2} ]388 o[-1] = o389 buf = self.archiverClass.archivedDataWithRootObject_(o)390 self.assertIsInstance(buf, NSData)391 v = self.unarchiverClass.unarchiveObjectWithData_(buf)392 self.assertIsInstance(v, list)393 self.assertIs(v[-1], v)394 self.assertEqual(v[:-1], o[:-1])395 def testNestedInstance(self):396 o = a_classic_class()397 o.value = o398 buf = self.archiverClass.archivedDataWithRootObject_(o)399 self.assertIsInstance(buf, NSData)400 v = self.unarchiverClass.unarchiveObjectWithData_(buf)401 self.assertIsInstance(v, a_classic_class)402 self.assertIs(v.value, v)403 def dont_testNestedInstanceWithReduce(self):404 # Test recursive instantation with a __reduce__ method405 #406 # This test is disabled because pickle doesn't support407 # this (and we don't either)408 o = a_reducing_class()409 o.value = o410 import pickle411 b = pickle.dumps(o)412 o2 = pickle.loads(b)413 buf = self.archiverClass.archivedDataWithRootObject_(o)414 self.assertIsInstance(buf, NSData)415 v = self.unarchiverClass.unarchiveObjectWithData_(buf)416 self.assertIsInstance(v, a_reducing_class)417 self.assertIs(v.value, v)418 def test_reducing_object(self):419 o = a_reducing_class()420 o.value = 42421 buf = self.archiverClass.archivedDataWithRootObject_(o)422 self.assertIsInstance(buf, NSData)423 v = self.unarchiverClass.unarchiveObjectWithData_(buf)424 self.assertIsInstance(v, a_reducing_class)425 self.assertEqual(o.value, 42)426 def testRecusiveNesting(self):427 l = []428 d = {1:l}429 i = a_classic_class()430 i.attr = d431 l.append(i)432 buf = self.archiverClass.archivedDataWithRootObject_(l)433 self.assertIsInstance(buf, NSData)434 v = self.unarchiverClass.unarchiveObjectWithData_(buf)435 self.assertEqual(len(v), 1)436 self.assertEqual(dir(v[0]), dir(i))437 self.assertEqual(list(v[0].attr.keys()), [1])438 self.assertIs(v[0].attr[1], v)439 buf = self.archiverClass.archivedDataWithRootObject_(d)440 self.assertIsInstance(buf, NSData)441 v = self.unarchiverClass.unarchiveObjectWithData_(buf)442 self.assertIs(v[1][0].attr, v)443 def testTupleOfObjects(self):444 o = a_classic_class()445 t = (o, o, o)446 buf = self.archiverClass.archivedDataWithRootObject_(t)447 self.assertIsInstance(buf, NSData)448 v = self.unarchiverClass.unarchiveObjectWithData_(buf)449 self.assertIsInstance(v, tuple)450 self.assertEqual(len(v), 3)451 self.assertIsInstance(v[0], a_classic_class)452 self.assertIs(v[0], v[1])453 self.assertIs(v[0], v[2])454class TestArchiveSimple (TestKeyedArchiveSimple):455 def setUp(self):456 self.archiverClass = NSArchiver457 self.unarchiverClass = NSUnarchiver458class TestKeyedArchivePlainPython (TestCase, test.pickletester.AbstractPickleTests):459 # Ensure that we don't run every test case three times460 def setUp(self):461 self._protocols = test.pickletester.protocols462 test.pickletester.protocols = (2,)463 def tearDown(self):464 test.pickletester.protocols = self._protocols465 def dumps(self, arg, proto=0, fast=0):466 # Ignore proto and fast467 return NSKeyedArchiver.archivedDataWithRootObject_(arg)468 def loads(self, buf):469 return NSKeyedUnarchiver.unarchiveObjectWithData_(buf)470 # Disable a number of methods, these test things we're not interested in.471 # (Most of these look at the generated byte-stream, as we're not writing data in pickle's472 # format such tests are irrelevant to archiving support)473 @onlyIf(0, "python unittest not relevant for archiving")474 def test_negative_put(self): pass475 @onlyIf(0, "python unittest not relevant for archiving")476 def test_int_pickling_efficiency(self): pass477 @onlyIf(0, "python unittest not relevant for archiving")478 def test_dynamic_class(self): pass479 @onlyIf(0, "python unittest not relevant for archiving")480 def test_ellipsis(self): pass481 @onlyIf(0, "python unittest not relevant for archiving")482 def test_notimplemented(self): pass483 @onlyIf(0, "python unittest not relevant for archiving")484 def test_load_classic_instance(self): pass485 @onlyIf(0, "python unittest not relevant for archiving")486 def test_insecure_strings(self): pass487 @onlyIf(0, "python unittest not relevant for archiving")488 def test_load_from_canned_string(self): pass489 @onlyIf(0, "python unittest not relevant for archiving")490 def test_maxint64(self): pass491 @onlyIf(0, "python unittest not relevant for archiving")492 def test_dict_chunking(self): pass493 @onlyIf(0, "python unittest not relevant for archiving")494 def test_float_format(self): pass495 @onlyIf(0, "python unittest not relevant for archiving")496 def test_garyp(self): pass497 @onlyIf(0, "python unittest not relevant for archiving")498 def test_list_chunking(self): pass499 @onlyIf(0, "python unittest not relevant for archiving")500 def test_singletons(self): pass501 @onlyIf(0, "python unittest not relevant for archiving")502 def test_simple_newobj(self): pass503 @onlyIf(0, "python unittest not relevant for archiving")504 def test_short_tuples(self): pass505 @onlyIf(0, "python unittest not relevant for archiving")506 def test_proto(self): pass507 @onlyIf(0, "python unittest not relevant for archiving")508 def test_long1(self): pass509 @onlyIf(0, "python unittest not relevant for archiving")510 def test_long4(self): pass511 @onlyIf(0, "python unittest not relevant for archiving")512 def test_get(self): pass513 @onlyIf(0, "python unittest not relevant for archiving")514 def test_load_from_data0(self): pass515 @onlyIf(0, "python unittest not relevant for archiving")516 def test_load_from_data1(self): pass517 @onlyIf(0, "python unittest not relevant for archiving")518 def test_load_from_data2(self): pass519 @onlyIf(0, "python unittest not relevant for archiving")520 def test_unpickle_from_2x(self): pass521 @onlyIf(0, "python unittest not relevant for archiving")522 def test_pickle_to_2x(self): pass523 @onlyIf(0, "python unittest not relevant for archiving")524 def test_bad_getattr(self): pass525 @onlyIf(0, "python unittest not relevant for archiving")526 def test_unicode(self): pass527 @onlyIf(0, "python unittest not relevant for archiving")528 def test_maxsize64(self): pass529 @onlyIf(0, "python unittest not relevant for archiving")530 def test_empty_bytestring(self): pass531 @onlyIf(0, "python unittest not relevant for archiving")532 def test_pop_empty_stack(self): pass533 def test_long(self):534 # The real test_long method takes way to much time, test a subset535 x = 12345678910111213141516178920 << (256*8)536 buf = self.dumps(x)537 v = self.loads(buf)538 self.assertEqual(v, x)539 x = -x540 buf = self.dumps(x)541 v = self.loads(buf)542 self.assertEqual(v, x)543 for val in (long(0), long(1), long(sys.maxsize), long(sys.maxsize * 128)):544 for x in val, -val:545 buf = self.dumps(x)546 v = self.loads(buf)547 self.assertEqual(v, x)548 # Overriden tests for extension codes, the test code checks549 # the actual byte stream.550 def produce_global_ext(self, extcode, opcode):551 e = test.pickletester.ExtensionSaver(extcode)552 try:553 copyreg.add_extension(__name__, "MyList", extcode)554 x = MyList([1, 2, 3])555 x.foo = 42556 x.bar = "hello"557 s1 = self.dumps(x, 1)558 y = self.loads(s1)559 self.assertEqual(list(x), list(y))560 self.assertEqual(x.__dict__, y.__dict__)561 finally:562 e.restore()563 #564 # The test_reduce* methods iterate over various protocol565 # versions. Override to only look at protocol version 2.566 #567 def test_reduce_overrides_default_reduce_ex(self):568 for proto in 2,:569 x = test.pickletester.REX_one()570 self.assertEqual(x._reduce_called, 0)571 s = self.dumps(x, proto)572 self.assertEqual(x._reduce_called, 1)573 y = self.loads(s)574 self.assertEqual(y._reduce_called, 0)575 def test_reduce_ex_called(self):576 for proto in 2,:577 x = test.pickletester.REX_two()578 self.assertEqual(x._proto, None)579 s = self.dumps(x, proto)580 self.assertEqual(x._proto, proto)581 y = self.loads(s)582 self.assertEqual(y._proto, None)583 def test_reduce_ex_overrides_reduce(self):584 for proto in 2,:585 x = test.pickletester.REX_three()586 self.assertEqual(x._proto, None)587 s = self.dumps(x, proto)588 self.assertEqual(x._proto, proto)589 y = self.loads(s)590 self.assertEqual(y._proto, None)591 def test_reduce_ex_calls_base(self):592 for proto in 2,:593 x = test.pickletester.REX_four()594 self.assertEqual(x._proto, None)595 s = self.dumps(x, proto)596 self.assertEqual(x._proto, proto)597 y = self.loads(s)598 self.assertEqual(y._proto, proto)599 def test_reduce_calls_base(self):600 for proto in 2,:601 x = test.pickletester.REX_five()602 self.assertEqual(x._reduce_called, 0)603 s = self.dumps(x, proto)604 self.assertEqual(x._reduce_called, 1)605 y = self.loads(s)606 self.assertEqual(y._reduce_called, 1)607class TestArchivePlainPython (TestKeyedArchivePlainPython):608 def setUp(self):609 self._protocols = test.pickletester.protocols610 test.pickletester.protocols = (2,)611 def tearDown(self):612 test.pickletester.protocols = self._protocols613 def dumps(self, arg, proto=0, fast=0):614 # Ignore proto and fast615 return NSArchiver.archivedDataWithRootObject_(arg)616 def loads(self, buf):617 return NSUnarchiver.unarchiveObjectWithData_(buf)618 @onlyIf(0, "python unittest not relevant for archiving")619 def test_negative_put(self): pass620 @onlyIf(0, "python unittest not relevant for archiving")621 def test_int_pickling_efficiency(self): pass622 @onlyIf(0, "python unittest not relevant for archiving")623 def test_negative_32b_binunicode(self): pass624 @onlyIf(0, "python unittest not relevant for archiving")625 def test_negative_32b_binput(self): pass626 @onlyIf(0, "python unittest not relevant for archiving")627 def test_negative_32b_binbytes(self): pass628#629# Disable testing of plain Archiving for now, need full support630# for keyed-archiving first, then worry about adding "classic"631# archiving.632#633#class TestArchivePlainPython (TestKeyedArchivePlainPython):634# def dumps(self, arg, proto=0, fast=0):635# # Ignore proto and fast636# return NSArchiver.archivedDataWithRootObject_(arg)637#638# def loads(self, buf):639# return NSUnarchiver.unarchiveObjectWithData_(buf)640#641# Second set of tests: test if archiving a graph that642# contains both python and objective-C objects works correctly.643#644class TestKeyedArchiveMixedGraphs (TestCase):645 def dumps(self, arg, proto=0, fast=0):646 # Ignore proto and fast647 return NSKeyedArchiver.archivedDataWithRootObject_(arg)648 def loads(self, buf):649 return NSKeyedUnarchiver.unarchiveObjectWithData_(buf)650 def test_list1(self):651 o1 = a_classic_class()652 o2 = a_newstyle_class()653 o2.lst = NSArray.arrayWithObject_(o1)654 l = NSArray.arrayWithArray_([o1, o2, [o1, o2]])655 buf = self.dumps(l)656 self.assertIsInstance(buf, NSData)657 out = self.loads(buf)658 self.assertIsInstance(out, NSArray)659 self.assertEqual(len(out), 3)660 p1 = out[0]661 p2 = out[1]662 p3 = out[2]663 self.assertIsInstance(p1, a_classic_class)664 self.assertIsInstance(p2, a_newstyle_class)665 self.assertIsInstance(p3, list)666 self.assertIs(p3[0], p1)667 self.assertIs(p3[1], p2)668 self.assertIsInstance(p2.lst , NSArray)669 self.assertIs(p2.lst[0], p1)670class TestArchiveMixedGraphs (TestKeyedArchiveMixedGraphs):671 def dumps(self, arg, proto=0, fast=0):672 # Ignore proto and fast673 return NSArchiver.archivedDataWithRootObject_(arg)674 def loads(self, buf):675 return NSUnarchiver.unarchiveObjectWithData_(buf)676#677# And finally some tests to check if archiving of Python678# subclasses of NSObject works correctly.679#680class TestArchivePythonObjCSubclass (TestCase):681 pass682if __name__ == "__main__":...
test_unarchive.py
Source:test_unarchive.py
1import pytest2from django.contrib.admin.templatetags.admin_urls import admin_urlname3from django.urls import reverse4from rest_framework import status5from datahub.company.models import Company, CompanyPermission6from datahub.company.test.factories import (7 ArchivedCompanyFactory,8 CompanyFactory,9 DuplicateCompanyFactory,10)11from datahub.core.test_utils import AdminTestMixin, create_test_user12from datahub.core.utils import reverse_with_query_string13class TestUnarchiveCompanyLink(AdminTestMixin):14 """15 Tests the 'unarchive' link on the change form.16 """17 def test_link_exists(self):18 """19 Test that the link exists for a user with the change company permission.20 """21 company = ArchivedCompanyFactory()22 change_route_name = admin_urlname(Company._meta, 'change')23 change_url = reverse(change_route_name, args=(company.pk,))24 response = self.client.get(change_url)25 assert response.status_code == status.HTTP_200_OK26 unarchive_route_name = admin_urlname(Company._meta, 'unarchive-company')27 unarchive_query_args = {28 'company': company.pk,29 }30 unarchive_url = reverse_with_query_string(31 unarchive_route_name,32 unarchive_query_args,33 )34 assert unarchive_url in response.rendered_content35 def test_link_does_not_exist_with_only_view_permission(self):36 """37 Test that the link does not exist for a user with only the view company permission.38 """39 company = ArchivedCompanyFactory()40 change_route_name = admin_urlname(Company._meta, 'change')41 change_url = reverse(change_route_name, args=(company.pk,))42 user = create_test_user(43 permission_codenames=(CompanyPermission.view_company,),44 is_staff=True,45 password=self.PASSWORD,46 )47 client = self.create_client(user=user)48 response = client.get(change_url)49 assert response.status_code == status.HTTP_200_OK50 unarchive_route_name = admin_urlname(Company._meta, 'unarchive-company')51 unarchive_url = reverse(unarchive_route_name)52 assert unarchive_url not in response.rendered_content53 @pytest.mark.parametrize(54 'company_creator',55 (56 # A company that has not been archived57 CompanyFactory,58 # A company that was archived as part of the merge process59 DuplicateCompanyFactory,60 ),61 )62 def test_link_does_not_exist_company_not_unarchivable(self, company_creator):63 """64 Test that the link does not exist when the company is not unarchivable.65 """66 company = company_creator()67 change_route_name = admin_urlname(Company._meta, 'change')68 change_url = reverse(change_route_name, args=(company.pk,))69 response = self.client.get(change_url)70 assert response.status_code == status.HTTP_200_OK71 unarchive_route_name = admin_urlname(Company._meta, 'unarchive-company')72 unarchive_url = reverse(unarchive_route_name)73 assert unarchive_url not in response.rendered_content74class TestUnarchiveCompanyViewGet(AdminTestMixin):75 """Tests GET requests for the 'unarchive company' view."""76 @pytest.mark.parametrize(77 'company_callable,expected_status_code,expected_archived_value',78 (79 # Unarchive of an archived company is successful80 (81 ArchivedCompanyFactory,82 status.HTTP_302_FOUND,83 False,84 ),85 # Unarchive of an non-archived company responds with bad request86 (87 CompanyFactory,88 status.HTTP_400_BAD_REQUEST,89 False,90 ),91 # Unarchive of a duplicate company responds with a 302, but does not unarchive the92 # company93 (94 DuplicateCompanyFactory,95 status.HTTP_302_FOUND,96 True,97 ),98 ),99 )100 def test_unarchive_view(101 self,102 company_callable,103 expected_status_code,104 expected_archived_value,105 ):106 """107 Test the unarchive view when called on companies in different states.108 """109 company = company_callable()110 unarchive_route_name = admin_urlname(Company._meta, 'unarchive-company')111 unarchive_query_args = {112 'company': company.pk,113 }114 unarchive_url = reverse_with_query_string(115 unarchive_route_name,116 unarchive_query_args,117 )118 response = self.client.get(unarchive_url)119 assert response.status_code == expected_status_code120 company.refresh_from_db()121 assert company.archived is expected_archived_value122 if expected_archived_value is False:123 assert not company.archived_on124 assert not company.archived_by125 assert not company.archived_reason126 def test_unarchive_company_does_not_exist(self):127 """128 Test that a 400 is returned when an invalid value is passed in the query string.129 This could only happen if the query string was manipulated, or the referenced company130 was deleted.131 """132 unarchive_route_name = admin_urlname(Company._meta, 'unarchive-company')133 unarchive_query_args = {134 'company': 'abc123',135 }136 unarchive_url = reverse_with_query_string(137 unarchive_route_name,138 unarchive_query_args,139 )140 response = self.client.get(unarchive_url)141 assert response.status_code == status.HTTP_400_BAD_REQUEST142 def test_unarchive_permission_denied(self):143 """144 Test the unarchive view when the user does not have sufficient permissions145 to unarchive a company.146 """147 company = ArchivedCompanyFactory()148 unarchive_route_name = admin_urlname(Company._meta, 'unarchive-company')149 unarchive_query_args = {150 'company': company.pk,151 }152 unarchive_url = reverse_with_query_string(153 unarchive_route_name,154 unarchive_query_args,155 )156 user = create_test_user(157 permission_codenames=(CompanyPermission.view_company,),158 is_staff=True,159 password=self.PASSWORD,160 )161 client = self.create_client(user=user)162 response = client.get(unarchive_url)163 assert response.status_code == status.HTTP_403_FORBIDDEN164 company.refresh_from_db()...
test_unarchive_car_view.py
Source:test_unarchive_car_view.py
1from django.test import TestCase, Client2from Garage.models import Car, \3 User4c = Client()5username = 'testuser'6password = '1234567890'7class TestUnarchiveCar(TestCase):8 @classmethod9 def setUpTestData(cls):10 user = User.objects.create_user(11 username='testuser',12 first_name='Test',13 last_name='T',14 email='test@test.test',15 is_active=True16 )17 user.set_password('1234567890')18 user.save()19 Car.objects.create(20 producer='Test Unarchive Car',21 model='car',22 year=2003,23 transmission=9,24 fuel=6,25 drive_system=2,26 archive=True,27 user=user28 )29 def test_not_logged_in_user_redirects_to_login_page(self):30 car = Car.objects.get(producer='Test Unarchive Car')31 response = c.get(f'/car/unarchive/{car.id}')32 self.assertRedirects(response, f'/accounts/login/?next=/car/unarchive/{car.id}', 302)33 def test_loggin(self):34 logged_in = c.login(username=username, password=password)35 self.assertTrue(logged_in)36 def test_logged_in_user_with_wrong_car_id_receives_404_error(self):37 c.login(username=username, password=password)38 response = c.get('/car/unarchive/2')39 self.assertEqual(response.status_code, 404)40 def test_render_unarchive_car_view_for_logged_in_user(self):41 car = Car.objects.get(producer='Test Unarchive Car')42 c.login(username=username, password=password)43 response = c.get(f'/car/unarchive/{car.id}')44 self.assertEqual(response.status_code, 200)45 def test_render_template_for_logged_in_user(self):46 c.login(username=username, password=password)47 car = Car.objects.get(producer='Test Unarchive Car')48 response = c.get(f'/car/unarchive/{car.id}')49 self.assertTemplateUsed(response, 'Garage/unarchive_car.html')50 def test_logged_in_user_returns_car_from_the_archive(self):51 c.login(username=username, password=password)52 car = Car.objects.get(producer='Test Unarchive Car')53 response = c.get(f'/car/unarchive/{car.id}')54 self.assertEqual(response.status_code, 200)55 r = c.post(f'/car/unarchive/{car.id}')56 car_re_requested = Car.objects.get(producer='Test Unarchive Car')57 self.assertFalse(car_re_requested.archive)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!