Best Python code snippet using hypothesis
tests.py
Source:tests.py
1from django.test import TestCase, Client2from django.contrib.auth.models import User3from .models import Mail4from .models import Route5from .models import Attachment6#from django.core.management import call_command7import simplejson as json8from pprint import pprint9import datetime10# Create your tests here.11# class JenkinsTest(TestCase):12# def test_what_if_fail(self):13# self.assertEqual(1,3)14#call_command('flush','--noinput')15class myTestCase(TestCase):16 def setUp(self):17 frank = User.objects.create_user(username='Frank',18 password='whatevs',19 first_name='Testislez',20 last_name='Person')21 ned = User.objects.create_user(username='Ned',22 password='whatevas',23 first_name='Ned',24 last_name='Person')25 # Message with an attachment that is for Frank26 mailmsg = Mail.objects.create(content='Test Message',27 subject='test message for Frank',28 fk_sender=ned,29 termcode="172s",30 section="21232")31 Route.objects.create(to='frank',32 read=False,33 fk_mail=mailmsg)34 # Attachment.objects.create(filepath='/mnt/maildata',35 # filename='tatadfa.doc',36 # fk_mail=mailmsg37 # )38 # Messsage for frank that does not have an attachment39 mailmsg = Mail.objects.create(content='Test message for frank',40 subject='No Attachment for frank',41 fk_sender=ned,42 termcode = "172s",43 section = "21231")44 Route.objects.create(to='frank',45 read=False,46 fk_mail=mailmsg)47 # Message for "Ned"48 mailmsg = Mail.objects.create(content='Test Message 3',49 subject='test subject for Ned',50 fk_sender=frank,51 termcode="172s",52 section="21232"53 )54 Route.objects.create(to=str(ned.username),55 read=False,56 fk_mail=mailmsg)57 # Attachment.objects.create(filepath='/mnt/maildata',58 # filename='tatadfa2.doc',59 # fk_mail=mailmsg60 # )61 # A Message to frank that is read62 mailmsg = Mail.objects.create(content='Test Message 4',63 subject='test email read',64 fk_sender=ned,65 termcode="172s",66 section="21231"67 )68 Route.objects.create(to=frank.username,69 read=True,70 fk_mail=mailmsg)71 # Attachment.objects.create(filepath='/mnt/maildata',72 # filename='tatadfa3.doc',73 # fk_mail=mailmsg74 # )75class MarkMailUnreadTest(myTestCase):76 def test_bad_users_cannot_markunread(self):77 c = Client()78 res = c.login(username='Frank', password='whatevs')79 mailmsg = Mail.objects.create(content='Test REPLY',80 subject='test timestamp for Ned',81 fk_sender=User.objects.get(username="Frank"),82 termcode="172s",83 section="21231",84 )85 Route.objects.create(to=User.objects.get(username="Ned").username,86 read=False,87 fk_mail=mailmsg)88 res = c.post('/munread/', {"message_id":mailmsg.id})89 self.assertEqual(res.status_code, 403)90 def test_good_users_can_markunread(self):91 c = Client()92 res = c.login(username='Frank', password='whatevs')93 mailmsg = Mail.objects.create(content='Test REPLY',94 subject='test timestamp for Ned',95 fk_sender=User.objects.get(username="Ned"),96 termcode="172s",97 section="21231",98 )99 Route.objects.create(to=User.objects.get(username="Frank").username,100 read=False,101 fk_mail=mailmsg)102 res = c.post('/archive/', {"message_id":mailmsg.id})103 self.assertEqual(res.status_code, 302)104class ArchiveTest(myTestCase):105 def test_bad_users_cannot_archive(self):106 c = Client()107 res = c.login(username='Frank', password='whatevs')108 mailmsg = Mail.objects.create(content='Test REPLY',109 subject='test timestamp for Ned',110 fk_sender=User.objects.get(username="Frank"),111 termcode="172s",112 section="21231",113 )114 Route.objects.create(to=User.objects.get(username="Ned").username,115 read=False,116 fk_mail=mailmsg)117 res = c.post('/archive/', {"message_id":mailmsg.id})118 self.assertEqual(res.status_code, 403)119 def test_good_users_can_archive_mail(self):120 c = Client()121 res = c.login(username='Frank', password='whatevs')122 mailmsg = Mail.objects.create(content='Test REPLY',123 subject='test timestamp for Ned',124 fk_sender=User.objects.get(username="Ned"),125 termcode="172s",126 section="21231",127 )128 Route.objects.create(to=User.objects.get(username="Frank"),129 read=False,130 fk_mail=mailmsg)131 res = c.post('/archive/', {"message_id":mailmsg.id})132 self.assertEqual(res.status_code, 302)133class InboxTest(myTestCase):134 def test_bad_users_have_no_access(self):135 c = Client()136 res = c.get('/')137 self.assertEqual(res.status_code, 403)138 def test_can_login(self):139 c = Client()140 res = c.login(username='Frank', password='whatevs')141 reslogin = c.get('/')142 self.assertEqual(reslogin.status_code, 200)143 def test_can_see_email(self):144 c = Client()145 res = c.login(username='Frank', password='whatevs')146 reslogin = c.get('/listEmail/')147 exists = False148 data = json.loads(reslogin.content)149 for message in data['messages']:150 pprint(message)151 if message['subject'] == "test message for Frank":152 exists = True153 self.assertTrue(exists)154 def test_cannot_see_wrong_email(self):155 c = Client()156 res = c.login(username='Frank', password='whatevs')157 reslogin = c.get('/listEmail/')158 exists = False159 data = json.loads(reslogin.content)160 for message in data['messages']:161 if message['subject'] == "test subject for Ned":162 exists = True163 self.assertFalse(exists)164 # def test_can_see_attachments(self):165 # c = Client()166 # res = c.login(username='Frank', password='whatevs')167 # reslogin = c.get('/')168 # exists = False169 # for message in reslogin.context['email']:170 # if message['has_attachment']:171 # exists = True172 # self.assertTrue(exists)173 def test_email_has_right_date(self):174 mailmsg = Mail.objects.create(content='Test timestamp',175 subject='test timestamp for Ned',176 fk_sender=User.objects.get(username="Frank"),177 termcode="172s",178 section="21231"179 )180 self.assertEqual(datetime.datetime.now().day, mailmsg.created.day)181 # def test_user_gets_a_list_of_unique_courses(self):182 # c = Client()183 # res = c.login(username='Frank', password='whatevs')184 # reslogin = c.get('/')185 # #print(reslogin.context['courses'])186 # self.assertTrue(allUnique(reslogin.context['courses']))187class ReplyTest(myTestCase):188 def test_user_can_see_mail(self):189 c = Client()190 mailmsg = Mail.objects.create(content='Test REPLY',191 subject='test timestamp for Ned',192 fk_sender=User.objects.get(username="Ned"),193 termcode="172s",194 section="21231",195 )196 Route.objects.create(to=User.objects.get(username="Frank").username,197 read=False,198 fk_mail=mailmsg)199 c.login(username='Frank', password='whatevs')200 reslogin = c.get('/reply/' + str(mailmsg.id), follow=True)201 self.assertEqual(reslogin.status_code, 200)202 def test_user_cannot_see_other_users_mail(self):203 c = Client()204 mailmsg = Mail.objects.create(content='Test REPLY',205 subject='test timestamp for Ned',206 fk_sender=User.objects.get(username="Frank"),207 termcode="172s",208 section="21231",209 )210 Route.objects.create(to=User.objects.get(username="Ned").username,211 read=False,212 fk_mail=mailmsg)213 c.login(username='Frank', password='whatevs')214 reslogin = c.get('/reply/' + str(mailmsg.id), follow=True)215 self.assertEqual(reslogin.status_code, 403)216 def test_message_gets_marked_as_read_on_open(self):217 c = Client()218 mailmsg = Mail.objects.create(content='Test REPLY',219 subject='test timestamp for Ned',220 fk_sender=User.objects.get(username="Frank"),221 termcode="172s",222 section="21231",223 )224 Route.objects.create(to=User.objects.get(username="Ned").username,225 read=False,226 fk_mail=mailmsg)227 c.login(username='Ned', password='whatevas')228 c.get('/reply/' + str(mailmsg.id), follow=True)229 self.assertTrue(Route.objects.get(fk_mail=mailmsg).read)230class LabelTest(myTestCase):231 def test_label_view_only_lists_email_for_class(self):232 c = Client()233 res = c.login(username='Frank', password='whatevs')234 reslogin = c.get('/label/21231-172s/')235 exists = False236 for message in reslogin.context['email']:237 if message['section'] == "21231":238 exists = True239 self.assertTrue(exists)240 def test_label_can_not_view_only_lists_email_for_class(self):241 c = Client()242 res = c.login(username='Frank', password='whatevs')243 reslogin = c.get('/label/21232-172s/')244 exists = False245 for message in reslogin.context['email']:246 if message['section'] == "21231":247 exists = True248 self.assertFalse(exists)249class ListUnreadTest(myTestCase):250 def test_for_unread_mail(self):251 #TODO fix it, fix it.252 self.assertTrue(True)253 # c = Client()254 # res = c.login(username='Frank', password='whatevs')255 # data = []256 # data.append({"course": '21231-172s'})257 # data.append({"course": '21232-172s'})258 # reslogin = c.post('/listunread/', json.dumps(data), content_type='application/json')259 # data = json.loads(reslogin.content)260 # self.assertEqual(data["0"]['count'], 1)261 # self.assertEqual(data["1"]['count'], 1)262class ComposeTest(myTestCase):263 def test_bad_users_have_no_access(self):264 c = Client()265 res = c.get('/compose/')266 self.assertEqual(res.status_code, 403)267 def test_can_login(self):268 c = Client()269 res = c.login(username='Frank', password='whatevs')270 reslogin = c.get('/compose/')271 self.assertEqual(reslogin.status_code, 200)272 def test_can_see_compose(self):273 c = Client()274 res = c.login(username='Frank', password='whatevs')275 reslogin = c.get('/compose/')276 exists = True277 # TODO make it test for view278 self.assertEqual(reslogin.status_code, 200)279class OutboxTest(myTestCase):280 def test_bad_users_have_no_access(self):281 tt = Client()282 res = tt.get('/outbox/')283 self.assertEqual(res.status_code, 403)284 def test_can_login(self):285 c = Client()286 res = c.login(username='Frank', password='whatevs')287 reslogin = c.get('/outbox/')288 self.assertEqual(reslogin.status_code, 200)289 def test_can_see_outbox(self):290 c = Client()291 res = c.login(username='Frank', password='whatevs')292 reslogin = c.get('/outbox/')293 exists = False294 # TODO make it test for view295 for message in reslogin.context['email']:296 if message['subject'] == "test subject for Ned":297 exists = True298 self.assertTrue(exists)299 def test_can_see_sent_email(self):300 mailmsg = Mail.objects.create(content='Test REPLY',301 subject='test timestamp for Ned',302 fk_sender=User.objects.get(username="Frank"),303 termcode="172s",304 section="21231",305 )306 Route.objects.create(to='Ned',307 read=False,308 fk_mail=mailmsg)309 c = Client()310 res = c.login(username='Frank', password='whatevs')311 reslogin = c.get('/outbox/')312 exists = False313 for message in reslogin.context['email']:314 if message['subject'] == "test timestamp for Ned":315 exists = True316 self.assertTrue(exists)317 def can_see_sent_email_even_if_usr_no_exist(self):318 mailmsg = Mail.objects.create(content='Test REPLY',319 subject='test timestamp for Ned',320 fk_sender=User.objects.get(username="Frank"),321 termcode="172s",322 section="21231",323 )324 Route.objects.create(to='Narkles',325 read=False,326 fk_mail=mailmsg)327 c = Client()328 res = c.login(username='Frank', password='whatevs')329 reslogin = c.get('/outbox/')330 exists = False331 for message in reslogin.context['email']:332 if message['subject'] == "test timestamp for Ned":333 exists = True334 self.assertTrue(exists)335class OutboxReplyTest(myTestCase):336 def test_bad_users_have_no_access(self):337 tt = Client()338 res = tt.get('/outbox/')339 self.assertEqual(res.status_code, 403)340 def test_can_reply_from_outbox(self):341 c = Client()342 res = c.login(username='Frank', password='whatevs')343 mailmsg = Mail.objects.create(content='Test REPLY',344 subject='test timestamp for Ned',345 fk_sender=User.objects.get(username="Frank"),346 termcode="172s",347 section="21231",348 )349 Route.objects.create(to=User.objects.get(username="Ned").username,350 read=False,351 fk_mail=mailmsg)352 resout = c.get('/or/'+str(mailmsg.id)+"/")353 self.assertEqual(resout.status_code, 200)354class ComposeViewTest(myTestCase):355 def test_form_valid(self):356 c = Client()357 res = c.login(username='Frank', password='whatevs')358 user = User.objects.get(username="Frank")359 to_user = User.objects.get(username="Ned")360 data = {361 "content":"This is the test content",362 "subject":"this is a test subject",363 "termcode":"173s",364 "section":"3000",365 "fk_sender": user.id,366 "sendto": to_user.id367 }368 res = c.post('/compose/',data)369 self.assertEqual(res.url, '/')370 def test_form_invalid(self):371 c = Client()372 res = c.login(username='Frank', password='whatevs')373 user = User.objects.get(username="Frank")374 to_user = User.objects.get(username="Ned")375 data = {376 "content":"This is the test content",377 "subject":"this is a test subject",378 "termcode":"173s",379 "section":"3000",380 "fk_sender": user.id,381 }382 res = c.post('/compose/', data)383 self.assertFormError(res, 'form', 'sendto', 'This field is required.')384 # def test_form_valid_with_attachment(self):385 # c = Client()386 # res = c.login(username='Frank', password='whatevs')387 # user = User.objects.get(username="Frank")388 # to_user = User.objects.get(username="Ned")389 # fp = open('README.md', 'rb')390 # data = {391 # "content":"This is the test content",392 # "subject":"this is a test subject",393 # "termcode":"173s",394 # "section":"3000",395 # "fk_sender": user.id,396 # "sendto": to_user.id,397 # "attachments": fp398 # }399 # res = c.post('/compose/',data)400 # self.assertEqual(res.url, '/')401class ReplyViewTest(myTestCase):402 def test_user_can_view_proper_reply(self):403 c = Client()404 res = c.login(username='Frank', password='whatevs')405 msg = Route.objects.filter(to="Frank")[0].fk_mail406 res = c.get('/reply/{}/'.format(msg.id))407 self.assertEqual(res.status_code, 200)408 def test_user_cannot_view_others(self):409 c = Client()410 res = c.login(username='Frank', password='whatevs')411 msg = Route.objects.filter(to="Ned")[0].fk_mail412 res = c.get('/reply/{}/'.format(msg.id))413 self.assertEqual(res.status_code, 403)414 def test_form_valid(self):415 c = Client()416 res = c.login(username='Frank', password='whatevs')417 user = User.objects.get(username="Frank")418 to_user = User.objects.get(username="Ned")419 msg = Route.objects.filter(to="Frank")[0].fk_mail420 data = {421 "content":"This is the test content",422 "subject":"this is a test subject",423 "termcode":"173s",424 "section":"3000",425 "fk_sender": user.id,426 "sendto": to_user.id427 }428 res = c.post('/reply/{}/'.format(msg.id),data)429 self.assertEqual(res.url, '/')430 def test_form_invalid(self):431 c = Client()432 res = c.login(username='Frank', password='whatevs')433 user = User.objects.get(username="Frank")434 to_user = User.objects.get(username="Ned")435 msg = Route.objects.filter(to="Frank")[0].fk_mail436 data = {437 "content":"This is the test content",438 "subject":"this is a test subject",439 "termcode":"173s",440 "section":"3000",441 "fk_sender": user.id,442 }443 res = c.post('/reply/{}/'.format(msg.id), data)444 self.assertFormError(res, 'form', 'sendto', 'This field is required.')445#------------------------------------------------------446def allUnique(x):447 seen = set()...
test_services.py
Source:test_services.py
1import os2import uuid3from flask import current_app4from mock import ANY, call, Mock, patch5import pytest6import calibration.services as cs7class TestServicesUnit(object):8 @patch('calibration.services.get_documents_from_criteria')9 def test_find_distortion_sets_calls_expected_functions(self,10 cs_get_documents_from_criteria):11 cs_get_documents_from_criteria.return_value = 'meh'12 return_val = cs.find_distortion_sets({'sponge': 'bob'})13 cs_get_documents_from_criteria.assert_called_once_with({'sponge': 'bob', 'type': 'distortion_set'})14 assert return_val == 'meh'15 @patch('calibration.services.get_documents_from_criteria')16 def test_find_distortion_pairs_calls_expected_functions(self,17 cs_get_documents_from_criteria):18 cs_get_documents_from_criteria.return_value = 'meh'19 return_val = cs.find_distortion_pairs({'sponge': 'bob'})20 cs_get_documents_from_criteria.assert_called_once_with({'sponge': 'bob', 'type': 'distortion_pair'})21 assert return_val == 'meh'22 @patch('calibration.services.get_documents_from_criteria')23 def test_find_calibration_sessions_calls_expected_functions(self,24 cs_get_documents_from_criteria):25 cs_get_documents_from_criteria.return_value = 'meh'26 return_val = cs.find_calibration_sessions({'sponge': 'bob'})27 cs_get_documents_from_criteria.assert_called_once_with({'sponge': 'bob', 'type': 'calibration_session'})28 assert return_val == 'meh'29 @patch('calibration.services.get_document_with_exception')30 def test_get_distortion_set_document_calls_expected_functions(self,31 cs_get_document_with_exception):32 cs_get_document_with_exception.return_value = {'whatevs': 'dont_care'}33 return_val = cs.get_distortion_set_document('jibba_jabba')34 cs_get_document_with_exception.assert_called_once_with('jibba_jabba', document_type='distortion_set')35 assert return_val == {'whatevs': 'dont_care'}36 @patch('calibration.services.get_document_with_exception')37 def test_get_distortion_pair_document_calls_expected_functions(self,38 cs_get_document_with_exception):39 cs_get_document_with_exception.return_value = {'whatevs': 'dont_care'}40 return_val = cs.get_distortion_pair_document('jibba_jabba')41 cs_get_document_with_exception.assert_called_once_with('jibba_jabba', document_type='distortion_pair')42 assert return_val == {'whatevs': 'dont_care'}43 @patch('calibration.services.get_document_with_exception')44 def test_get_calibration_session_document_calls_expected_functions(self,45 cs_get_document_with_exception):46 cs_get_document_with_exception.return_value = {'whatevs': 'dont_care'}47 return_val = cs.get_calibration_session_document('jibba_jabba')48 cs_get_document_with_exception.assert_called_once_with('jibba_jabba', document_type='calibration_session')...
test_security.py
Source:test_security.py
1"""2Tests for `security` module.3"""4from unittest.mock import MagicMock5import pytest6from omnic.config.utils import use_settings7from omnic.web import security8normalized_settings = dict(9 hmac_secret='dummy_secret',10 security='omnic.web.security.HmacSha1',11 allowed_locations={'whatevs.com'},12)13class TestHmacSha1Security:14 @pytest.mark.asyncio15 async def test_check(self):16 hm = security.HmacSha1()17 with use_settings(**normalized_settings):18 await hm.check('JPG', {19 'url': ['http://whatevs.com/stuff.png'],20 'digest': ['6d2a1495209af2d193affbb485d309a2e15bc5b1'],21 })22 # ensure case in-sensitivity and normalization of URL23 await hm.check('JPG', {24 'url': ['whatevs.com/stuff.png'],25 'digest': ['6D2A1495209AF2d193affBB485D309A2E15bc5b1'],26 })27 @pytest.mark.asyncio28 async def test_check_exceptions(self):29 hm = security.HmacSha1()30 with use_settings(**normalized_settings):31 with pytest.raises(security.SecurityException):32 await hm.check('JPG', {33 'url': ['http://whatevs.com/stuff.png'],34 'digest': ['a40246fdaa7e7201be545306f80a9e11'],35 })36 with pytest.raises(security.SecurityException):37 await hm.check('JPG', {38 'url': ['http://whatevs.com/stuff.png'],39 })40 with pytest.raises(security.SecurityException):41 await hm.check('JPG', {42 'digest': ['6d2a1495209af2d193affbb485d309a2e15bc5b1'],43 })44class TestSecurity:45 @pytest.mark.asyncio46 async def test_check(self):47 with use_settings(**normalized_settings):48 await security.check('JPG', {49 'url': ['http://whatevs.com/stuff.png'],50 'digest': ['6d2a1495209af2d193affbb485d309a2e15bc5b1'],51 })52 @pytest.mark.asyncio53 async def test_rewrite_middleware(self):54 with use_settings(**normalized_settings):55 mock_request = MagicMock()56 mock_request.path = '/stuff.png'57 server = MagicMock()58 ret_val = await security.rewrite_middleware(server, mock_request)59 assert mock_request.path == '/stuff.png'...
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!!