Best Python code snippet using Kiwi_python
signals.py
Source:signals.py
...30 self.assertEqual(a.save(), 1)31 self.assertTrue(a.id is not None)32 self.assertEqual(len(state), 2)33 self.assertEqual(state[-1], (A, a, a.id, False))34 def test_post_save(self):35 state = []36 @signals.post_save()37 def post_save(sender, instance, created):38 state.append((sender, instance, instance._pk, created))39 a = A()40 a.save()41 self.assertTrue(a.id is not None)42 self.assertEqual(state, [(A, a, a.id, True)])43 a.save()44 self.assertEqual(len(state), 2)45 self.assertEqual(state[-1], (A, a, a.id, False))46 def test_pre_delete(self):47 state = []48 @signals.pre_delete()49 def pre_delete(sender, instance):50 state.append((sender, instance, A.select().count()))51 a = A.create()52 self.assertEqual(a.delete_instance(), 1)53 self.assertEqual(state, [(A, a, 1)])54 def test_post_delete(self):55 state = []56 @signals.post_delete()57 def post_delete(sender, instance):58 state.append((sender, instance, A.select().count()))59 a = A.create()60 a.delete_instance()61 self.assertEqual(state, [(A, a, 0)])62 def test_pre_init(self):63 state = []64 A.create(a='a')65 @signals.pre_init()66 def pre_init(sender, instance):67 state.append((sender, instance.a))68 A.get()69 self.assertEqual(state, [(A, 'a')])70 def test_sender(self):71 state = []72 @signals.post_save(sender=A)73 def post_save(sender, instance, created):74 state.append(instance)75 m = A.create()76 self.assertEqual(state, [m])77 m2 = B.create()78 self.assertEqual(state, [m])79 def test_connect_disconnect(self):80 state = []81 @signals.post_save(sender=A)82 def post_save(sender, instance, created):83 state.append(instance)84 a = A.create()85 self.assertEqual(state, [a])86 # Signal was registered with a specific sender, so this fails.87 self.assertRaises(ValueError, signals.post_save.disconnect, post_save)88 # Disconnect signal, specifying sender.89 signals.post_save.disconnect(post_save, sender=A)90 # Signal handler has been unregistered.91 a2 = A.create()92 self.assertEqual(state, [a])93 # Re-connect without specifying sender.94 signals.post_save.connect(post_save)95 a3 = A.create()96 self.assertEqual(state, [a, a3])97 # Signal was not registered with a sender, so this fails.98 self.assertRaises(ValueError, signals.post_save.disconnect, post_save,99 sender=A)100 signals.post_save.disconnect(post_save)101 def test_function_reuse(self):102 state = []103 @signals.post_save(sender=A)104 def post_save(sender, instance, created):105 state.append(instance)106 # Connect function for sender=B as well.107 signals.post_save(sender=B)(post_save)108 a = A.create()109 b = B.create()110 self.assertEqual(state, [a, b])111 def test_subclass_instance_receive_signals(self):112 state = []113 @signals.post_save(sender=B)114 def post_save(sender, instance, created):115 state.append(instance)116 b = SubB.create()...
test_module.py
Source:test_module.py
1# Copyright 2012-2016 Canonical Ltd. This software is licensed under the2# GNU Affero General Public License version 3 (see the file LICENSE).3"""Tests for `maasserver.testing`."""4import http.client5from django.db.models.signals import post_save, pre_save6from django.http import HttpResponse, HttpResponseRedirect7from testtools.matchers import Equals8from maasserver.models.node import Node9from maasserver.testing import extract_redirect, NoReceivers10from maasserver.testing.factory import factory11from maasserver.testing.orm import reload_objects12from maasserver.testing.testcase import MAASServerTestCase13from maasserver.utils.orm import reload_object14class TestHelpers(MAASServerTestCase):15 """Test helper functions."""16 def test_extract_redirect_extracts_redirect_location(self):17 url = factory.make_string()18 self.assertEqual(url, extract_redirect(HttpResponseRedirect(url)))19 def test_extract_redirect_only_returns_target_path(self):20 url_path = factory.make_string()21 self.assertEqual(22 "/%s" % url_path,23 extract_redirect(24 HttpResponseRedirect("http://example.com/%s" % url_path)25 ),26 )27 def test_extract_redirect_errors_out_helpfully_if_not_a_redirect(self):28 content = factory.make_string(10).encode("ascii")29 other_response = HttpResponse(content=content)30 try:31 extract_redirect(other_response)32 except ValueError as e:33 self.assertThat(34 str(e),35 Equals(36 "Not a redirect: http status %d. Content: %s"37 % (http.client.OK.value, content)38 ),39 )40 def test_reload_object_reloads_object(self):41 test_obj = factory.make_Node()42 test_obj.save()43 Node.objects.filter(id=test_obj.id).update(hostname="newname")44 self.assertEqual("newname", reload_object(test_obj).hostname)45 def test_reload_object_returns_None_for_deleted_object(self):46 test_obj = factory.make_Node()47 test_obj.save()48 Node.objects.filter(id=test_obj.id).delete()49 self.assertIsNone(reload_object(test_obj))50 def test_reload_objects_reloads_objects(self):51 hostnames = ["name1", "name2", "name3"]52 objs = [factory.make_Node(hostname=hostname) for hostname in hostnames]53 for obj in objs:54 obj.save()55 hostnames[0] = "different"56 Node.objects.filter(id=objs[0].id).update(hostname=hostnames[0])57 self.assertItemsEqual(58 hostnames, [obj.hostname for obj in reload_objects(Node, objs)]59 )60 def test_reload_objects_omits_deleted_objects(self):61 objs = [factory.make_Node() for counter in range(3)]62 for obj in objs:63 obj.save()64 dead_obj = objs.pop(0)65 Node.objects.filter(id=dead_obj.id).delete()66 self.assertItemsEqual(objs, reload_objects(Node, objs))67class TestNoReceivers(MAASServerTestCase):68 def test_clears_and_restores_signal(self):69 # post_save already has some receivers on it, but make sure.70 self.assertNotEqual(0, len(post_save.receivers))71 old_values = list(post_save.receivers)72 with NoReceivers(post_save):73 self.assertEqual([], post_save.receivers)74 self.assertItemsEqual(old_values, post_save.receivers)75 def test_clears_and_restores_many_signals(self):76 self.assertNotEqual(0, len(post_save.receivers))77 self.assertNotEqual(0, len(pre_save.receivers))78 old_pre_values = pre_save.receivers79 old_post_values = post_save.receivers80 with NoReceivers((post_save, pre_save)):81 self.assertEqual([], post_save.receivers)82 self.assertEqual([], pre_save.receivers)83 self.assertItemsEqual(old_pre_values, pre_save.receivers)84 self.assertItemsEqual(old_post_values, post_save.receivers)85 def test_leaves_some_other_signals_alone(self):86 self.assertNotEqual(0, len(post_save.receivers))87 old_pre_values = pre_save.receivers88 with NoReceivers(post_save):...
models.py
Source:models.py
1"""2Testing signals before/after saving and deleting.3"""4from django.db import models5class Person(models.Model):6 first_name = models.CharField(max_length=20)7 last_name = models.CharField(max_length=20)8 def __unicode__(self):9 return u"%s %s" % (self.first_name, self.last_name)10def pre_save_test(signal, sender, instance, **kwargs):11 print 'pre_save signal,', instance12 if kwargs.get('raw'):13 print 'Is raw'14def post_save_test(signal, sender, instance, **kwargs):15 print 'post_save signal,', instance16 if 'created' in kwargs:17 if kwargs['created']:18 print 'Is created'19 else:20 print 'Is updated'21 if kwargs.get('raw'):22 print 'Is raw'23def pre_delete_test(signal, sender, instance, **kwargs):24 print 'pre_delete signal,', instance25 print 'instance.id is not None: %s' % (instance.id != None)26# #8285: signals can be any callable27class PostDeleteHandler(object):28 def __call__(self, signal, sender, instance, **kwargs):29 print 'post_delete signal,', instance30 print 'instance.id is None: %s' % (instance.id == None)31post_delete_test = PostDeleteHandler()32__test__ = {'API_TESTS':"""33# Save up the number of connected signals so that we can check at the end34# that all the signals we register get properly unregistered (#9989)35>>> pre_signals = (len(models.signals.pre_save.receivers),36... len(models.signals.post_save.receivers),37... len(models.signals.pre_delete.receivers),38... len(models.signals.post_delete.receivers))39>>> models.signals.pre_save.connect(pre_save_test)40>>> models.signals.post_save.connect(post_save_test)41>>> models.signals.pre_delete.connect(pre_delete_test)42>>> models.signals.post_delete.connect(post_delete_test)43>>> p1 = Person(first_name='John', last_name='Smith')44>>> p1.save()45pre_save signal, John Smith46post_save signal, John Smith47Is created48>>> p1.first_name = 'Tom'49>>> p1.save()50pre_save signal, Tom Smith51post_save signal, Tom Smith52Is updated53# Calling an internal method purely so that we can trigger a "raw" save.54>>> p1.save_base(raw=True)55pre_save signal, Tom Smith56Is raw57post_save signal, Tom Smith58Is updated59Is raw60>>> p1.delete()61pre_delete signal, Tom Smith62instance.id is not None: True63post_delete signal, Tom Smith64instance.id is None: False65>>> p2 = Person(first_name='James', last_name='Jones')66>>> p2.id = 9999967>>> p2.save()68pre_save signal, James Jones69post_save signal, James Jones70Is created71>>> p2.id = 9999872>>> p2.save()73pre_save signal, James Jones74post_save signal, James Jones75Is created76>>> p2.delete()77pre_delete signal, James Jones78instance.id is not None: True79post_delete signal, James Jones80instance.id is None: False81>>> Person.objects.all()82[<Person: James Jones>]83>>> models.signals.post_delete.disconnect(post_delete_test)84>>> models.signals.pre_delete.disconnect(pre_delete_test)85>>> models.signals.post_save.disconnect(post_save_test)86>>> models.signals.pre_save.disconnect(pre_save_test)87# Check that all our signals got disconnected properly.88>>> post_signals = (len(models.signals.pre_save.receivers),89... len(models.signals.post_save.receivers),90... len(models.signals.pre_delete.receivers),91... len(models.signals.post_delete.receivers))92>>> pre_signals == post_signals93True...
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!!