Best Python code snippet using nose
talk.py
Source:talk.py
1# -*- coding: utf-8 -*-2from akad.ttypes import Message3from random import randint4import json, ntpath5def loggedIn(func):6 def checkLogin(*args, **kwargs):7 if args[0].isLogin:8 return func(*args, **kwargs)9 else:10 args[0].callback.other("You want to call the function, you must login to LINE")11 return checkLogin12class LineTalk(object):13 isLogin = False14 _messageReq = {}15 _unsendMessageReq = 016 def __init__(self):17 self.isLogin = True18 """User"""19 @loggedIn20 def getProfile(self):21 return self.talk.getProfile()22 @loggedIn23 def getSettings(self):24 return self.talk.getSettings()25 @loggedIn26 def getUserTicket(self):27 return self.talk.getUserTicket()28 @loggedIn29 def updateProfile(self, profileObject):30 return self.talk.updateProfile(0, profileObject)31 @loggedIn32 def updateSettings(self, settingObject):33 return self.talk.updateSettings(0, settingObject)34 @loggedIn35 def updateProfileAttribute(self, attrId, value):36 return self.talk.updateProfileAttribute(0, attrId, value)37 """Operation"""38 @loggedIn39 def fetchOperation(self, revision, count):40 return self.talk.fetchOperations(revision, count)41 @loggedIn42 def getLastOpRevision(self):43 return self.talk.getLastOpRevision()44 """Message"""45 @loggedIn46 def sendMessage(self, to, text, contentMetadata={}, contentType=0):47 msg = Message()48 msg.to, msg._from = to, self.profile.mid49 msg.text = text50 msg.contentType, msg.contentMetadata = contentType, contentMetadata51 if to not in self._messageReq:52 self._messageReq[to] = -153 self._messageReq[to] += 154 return self.talk.sendMessage(self._messageReq[to], msg)55 56 """ Usage:57 @to Integer58 @text String59 @dataMid List of user Mid60 """61 @loggedIn62 def sendText(self, Tomid, text):63 msg = Message()64 msg.to = Tomid65 msg.text = text66 return self.talk.sendMessage(0, msg)67 @loggedIn68 def sendMessage1(self, messageObject):69 return self.talk.sendMessage(0,messageObject) 70 71 @loggedIn72 def sendMessageWithMention(self, to, text='', dataMid=[]):73 arr = []74 list_text=''75 if '[list]' in text.lower():76 i=077 for l in dataMid:78 list_text+='\n@[list-'+str(i)+']'79 i=i+180 text=text.replace('[list]', list_text)81 elif '[list-' in text.lower():82 text=text83 else:84 i=085 for l in dataMid:86 list_text+=' @[list-'+str(i)+']'87 i=i+188 text=text+list_text89 i=090 for l in dataMid:91 mid=l92 name='@[list-'+str(i)+']'93 ln_text=text.replace('\n',' ')94 if ln_text.find(name):95 line_s=int(ln_text.index(name))96 line_e=(int(line_s)+int(len(name)))97 arrData={'S': str(line_s), 'E': str(line_e), 'M': mid}98 arr.append(arrData)99 i=i+1100 contentMetadata={'MENTION':str('{"MENTIONEES":' + json.dumps(arr).replace(' ','') + '}')}101 return self.sendMessage(to, text, contentMetadata)102 @loggedIn103 def sendSticker(self, to, packageId, stickerId):104 contentMetadata = {105 'STKVER': '100',106 'STKPKGID': packageId,107 'STKID': stickerId108 }109 return self.sendMessage(to, '', contentMetadata, 7)110 111 @loggedIn112 def sendContact(self, to, mid):113 contentMetadata = {'mid': mid}114 return self.sendMessage(to, '', contentMetadata, 13)115 @loggedIn116 def sendGift(self, productId, productType):117 if productType not in ['theme','sticker']:118 raise Exception('Invalid productType value')119 contentMetadata = {120 'MSGTPL': str(randint(0, 12)),121 'PRDTYPE': productType.upper(),122 'STKPKGID' if productType == 'sticker' else 'PRDID': productId123 }124 return self.sendMessage(to, '', contentMetadata, 9)125 @loggedIn126 def unsendMessage(self, messageId):127 self._unsendMessageReq += 1128 return self.talk.unsendMessage(self._unsendMessageReq, messageId)129 @loggedIn130 def requestResendMessage(self, senderMid, messageId):131 return self.talk.requestResendMessage(self.revision, senderMid, messageId)132 @loggedIn133 def respondResendMessage(self, receiverMid, originalMessageId, resendMessage, errorCode):134 return self.talk.respondResendMessage(self.revision, receiverMid, originalMessageId, resendMessage, errorCode)135 @loggedIn136 def removeMessage(self, messageId):137 return self.talk.removeMessage(messageId)138 139 @loggedIn140 def removeAllMessages(self, lastMessageId):141 return self.talk.removeAllMessages(0, lastMessageId)142 143 @loggedIn144 def sendChatChecked(self, consumer, messageId):145 return self.talk.sendChatChecked(0, consumer, messageId)146 @loggedIn147 def sendEvent(self, messageObject):148 return self.talk.sendEvent(0, messageObject)149 @loggedIn150 def getLastReadMessageIds(self, chatId):151 return self.talk.getLastReadMessageIds(0,chatId)152 """Object"""153 @loggedIn154 def sendImage(self, to, path):155 objectId = self.sendMessage(to=to, text=None, contentType = 1).id156 return self.uploadObjTalk(path=path, type='image', returnAs='bool', objId=objectId)157 @loggedIn158 def sendImageWithURL(self, to, url):159 path = self.downloadFileURL(url, 'path')160 return self.sendImage(to, path)161 @loggedIn162 def sendGIF(self, to, path):163 return self.uploadObjTalk(path=path, type='gif', returnAs='bool', to=to)164 @loggedIn165 def sendGIFWithURL(self, to, url):166 path = self.downloadFileURL(url, 'path')167 return self.sendGIF(to, path)168 @loggedIn169 def sendVideo(self, to, path):170 objectId = self.sendMessage(to=to, text=None, contentMetadata={'VIDLEN': '60000','DURATION': '60000'}, contentType = 2).id171 return self.uploadObjTalk(path=path, type='video', returnAs='bool', objId=objectId)172 @loggedIn173 def sendVideoWithURL(self, to, url):174 path = self.downloadFileURL(url, 'path')175 return self.sendVideo(to, path)176 @loggedIn177 def sendAudio(self, to, path):178 objectId = self.sendMessage(to=to, text=None, contentType = 3).id179 return self.uploadObjTalk(path=path, type='audio', returnAs='bool', objId=objectId)180 @loggedIn181 def sendAudioWithURL(self, to, url):182 path = self.downloadFileURL(url, 'path')183 return self.sendAudio(to, path)184 @loggedIn185 def sendFile(self, to, path, file_name=''):186 if file_name == '':187 file_name = ntpath.basename(path)188 file_size = len(open(path, 'rb').read())189 objectId = self.sendMessage(to=to, text=None, contentMetadata={'FILE_NAME': str(file_name),'FILE_SIZE': str(file_size)}, contentType = 14).id190 return self.uploadObjTalk(path=path, type='file', returnAs='bool', objId=objectId)191 @loggedIn192 def sendFileWithURL(self, to, url, fileName=''):193 path = self.downloadFileURL(url, 'path')194 return self.sendFile(to, path, fileName)195 """Contact"""196 197 @loggedIn198 def blockContact(self, mid):199 return self.talk.blockContact(0, mid)200 @loggedIn201 def unblockContact(self, mid):202 return self.talk.unblockContact(0, mid)203 @loggedIn204 def findAndAddContactsByMid(self, mid):205 return self.talk.findAndAddContactsByMid(0, mid)206 @loggedIn207 def findAndAddContactsByUserid(self, userid):208 return self.talk.findAndAddContactsByUserid(0, userid)209 @loggedIn210 def findContactsByUserid(self, userid):211 return self.talk.findContactByUserid(userid)212 @loggedIn213 def findContactByTicket(self, ticketId):214 return self.talk.findContactByUserTicket(ticketId)215 @loggedIn216 def getAllContactIds(self):217 return self.talk.getAllContactIds()218 @loggedIn219 def getBlockedContactIds(self):220 return self.talk.getBlockedContactIds()221 @loggedIn222 def getContact(self, mid):223 return self.talk.getContact(mid)224 @loggedIn225 def getContacts(self, midlist):226 return self.talk.getContacts(midlist)227 @loggedIn228 def getFavoriteMids(self):229 return self.talk.getFavoriteMids()230 @loggedIn231 def getHiddenContactMids(self):232 return self.talk.getHiddenContactMids()233 @loggedIn234 def reissueUserTicket(self, expirationTime=100, maxUseCount=100):235 return self.talk.reissueUserTicket(expirationTime, maxUseCount)236 237 @loggedIn238 def cloneContactProfile(self, mid):239 contact = self.getContact(mid)240 profile = self.profile241 profile.displayName = contact.displayName242 profile.statusMessage = contact.statusMessage243 profile.pictureStatus = contact.pictureStatus244 self.updateProfileAttribute(8, profile.pictureStatus)245 return self.updateProfile(profile)246 """Group"""247 @loggedIn248 def getChatRoomAnnouncementsBulk(self, chatRoomMids):249 return self.talk.getChatRoomAnnouncementsBulk(chatRoomMids)250 @loggedIn251 def getChatRoomAnnouncements(self, chatRoomMid):252 return self.talk.getChatRoomAnnouncements(chatRoomMid)253 @loggedIn254 def createChatRoomAnnouncement(self, chatRoomMid, type, contents):255 return self.talk.createChatRoomAnnouncement(self.revision, chatRoomMid, type, contents)256 @loggedIn257 def removeChatRoomAnnouncement(self, chatRoomMid, announcementSeq):258 return self.talk.removeChatRoomAnnouncement(self.revision, chatRoomMid, announcementSeq)259 @loggedIn260 def getGroupWithoutMembers(self, groupId):261 return self.talk.getGroupWithoutMembers(groupId)262 263 @loggedIn264 def findGroupByTicket(self, ticketId):265 return self.talk.findGroupByTicket(ticketId)266 @loggedIn267 def acceptGroupInvitation(self, groupId):268 return self.talk.acceptGroupInvitation(0, groupId)269 @loggedIn270 def acceptGroupInvitationByTicket(self, groupId, ticketId):271 return self.talk.acceptGroupInvitationByTicket(0, groupId, ticketId)272 @loggedIn273 def cancelGroupInvitation(self, groupId, contactIds):274 return self.talk.cancelGroupInvitation(0, groupId, contactIds)275 @loggedIn276 def createGroup(self, name, midlist):277 return self.talk.createGroup(0, name, midlist)278 @loggedIn279 def getGroup(self, groupId):280 return self.talk.getGroup(groupId)281 @loggedIn282 def getGroups(self, groupIds):283 return self.talk.getGroups(groupIds)284 @loggedIn285 def getGroupIdsInvited(self):286 return self.talk.getGroupIdsInvited()287 @loggedIn288 def getGroupIdsJoined(self):289 return self.talk.getGroupIdsJoined()290 @loggedIn291 def inviteIntoGroup(self, groupId, midlist):292 return self.talk.inviteIntoGroup(0, groupId, midlist)293 @loggedIn294 def kickoutFromGroup(self, groupId, midlist):295 return self.talk.kickoutFromGroup(0, groupId, midlist)296 @loggedIn297 def leaveGroup(self, groupId):298 return self.talk.leaveGroup(0, groupId)299 @loggedIn300 def rejectGroupInvitation(self, groupId):301 return self.talk.rejectGroupInvitation(0, groupId)302 @loggedIn303 def reissueGroupTicket(self, groupId):304 return self.talk.reissueGroupTicket(groupId)305 @loggedIn306 def updateGroup(self, groupObject):307 return self.talk.updateGroup(0, groupObject)308 """Room"""309 @loggedIn310 def createRoom(self, midlist):311 return self.talk.createRoom(0, midlist)312 @loggedIn313 def getRoom(self, roomId):314 return self.talk.getRoom(roomId)315 @loggedIn316 def inviteIntoRoom(self, roomId, midlist):317 return self.talk.inviteIntoRoom(0, roomId, midlist)318 @loggedIn319 def leaveRoom(self, roomId):320 return self.talk.leaveRoom(0, roomId)321 """Call"""322 323 @loggedIn324 def acquireCallTalkRoute(self, to):...
test_logger.py
Source:test_logger.py
1# Copyright 2014-2016 Canonical Ltd. This software is licensed under the2# GNU Affero General Public License version 3 (see the file LICENSE).3"""Tests for log.py"""4import pathlib5import subprocess6import sys7from testtools.content import text_content8from maastesting.factory import factory9from maastesting.matchers import DocTestMatches10from maastesting.testcase import MAASTestCase11from provisioningserver.logger import LoggingMode12from provisioningserver.logger.testing import find_log_lines13from provisioningserver.utils import typed14from provisioningserver.utils.shell import get_env_with_locale15here = pathlib.Path(__file__).parent16@typed17def log_something(18 name: str, *, verbosity: int, set_verbosity: int = None, mode: LoggingMode19):20 env = dict(get_env_with_locale(), PYTHONPATH=":".join(sys.path))21 script = here.parent.joinpath("testing", "logsomething.py")22 args = [23 "--name",24 name,25 "--verbosity",26 "%d" % verbosity,27 "--mode",28 mode.name,29 ]30 if set_verbosity is not None:31 args.extend(["--set-verbosity", "%d" % set_verbosity])32 cmd = [sys.executable, str(script)] + args33 output = subprocess.check_output(cmd, env=env, stderr=subprocess.STDOUT)34 return output.decode("utf-8")35class TestLogging(MAASTestCase):36 """Test logging in MAAS as configured by `p.logger.configure`.37 The "twistd" tests reflect usage under `twistd`.38 The "command" tests reflect usage at an interactive terminal, like when39 invoking `maas-rackd`. The chief difference here is that neither stdout40 nor stderr are wrapped.41 """42 scenarios = (43 ("initial_only", {"initial_only": True, "increasing": False}),44 ("increasing_verbosity", {"initial_only": False, "increasing": True}),45 ("decreasing_verbosity", {"initial_only": False, "increasing": False}),46 )47 def _get_log_levels(self, verbosity_under_test: int):48 if self.initial_only:49 verbosity = verbosity_under_test50 set_verbosity = None51 elif self.increasing:52 verbosity = 053 set_verbosity = verbosity_under_test54 else:55 verbosity = 356 set_verbosity = verbosity_under_test57 return verbosity, set_verbosity58 def test_twistd_default_verbosity(self):59 verbosity, set_verbosity = self._get_log_levels(2)60 name = factory.make_name("log.name")61 logged = log_something(62 name,63 verbosity=verbosity,64 set_verbosity=set_verbosity,65 mode=LoggingMode.TWISTD,66 )67 self.addDetail("logged", text_content(logged))68 observed = find_log_lines(logged)69 expected = [70 (name, "info", "From `twisted.logger`."),71 (name, "warn", "From `twisted.logger`."),72 (name, "error", "From `twisted.logger`."),73 (name, "info", "From `twisted.python.log`."),74 ("logsomething", "info", "From `twisted.python.log.logfile`."),75 (name, "info", "From `logging`."),76 (name, "warn", "From `logging`."),77 (name, "error", "From `logging`."),78 ("maas." + name, "info", "From `get_maas_logger`."),79 ("maas." + name, "warn", "From `get_maas_logger`."),80 ("maas." + name, "error", "From `get_maas_logger`."),81 ("stdout", "info", "Printing to stdout."),82 ("stderr", "error", "Printing to stderr."),83 ("-", "warn", "UserWarning: This is a warning!"),84 ]85 self.assertSequenceEqual(expected, observed)86 def test_twistd_high_verbosity(self):87 verbosity, set_verbosity = self._get_log_levels(3)88 name = factory.make_name("log.name")89 logged = log_something(90 name,91 verbosity=verbosity,92 set_verbosity=set_verbosity,93 mode=LoggingMode.TWISTD,94 )95 self.addDetail("logged", text_content(logged))96 observed = find_log_lines(logged)97 expected = [98 (name, "debug", "From `twisted.logger`."),99 (name, "info", "From `twisted.logger`."),100 (name, "warn", "From `twisted.logger`."),101 (name, "error", "From `twisted.logger`."),102 (name, "info", "From `twisted.python.log`."),103 ("logsomething", "info", "From `twisted.python.log.logfile`."),104 (name, "debug", "From `logging`."),105 (name, "info", "From `logging`."),106 (name, "warn", "From `logging`."),107 (name, "error", "From `logging`."),108 ("maas." + name, "debug", "From `get_maas_logger`."),109 ("maas." + name, "info", "From `get_maas_logger`."),110 ("maas." + name, "warn", "From `get_maas_logger`."),111 ("maas." + name, "error", "From `get_maas_logger`."),112 ("stdout", "info", "Printing to stdout."),113 ("stderr", "error", "Printing to stderr."),114 ("-", "warn", "UserWarning: This is a warning!"),115 ]116 self.assertSequenceEqual(expected, observed)117 def test_twistd_low_verbosity(self):118 verbosity, set_verbosity = self._get_log_levels(1)119 name = factory.make_name("log.name")120 logged = log_something(121 name,122 verbosity=verbosity,123 set_verbosity=set_verbosity,124 mode=LoggingMode.TWISTD,125 )126 self.addDetail("logged", text_content(logged))127 observed = find_log_lines(logged)128 expected = [129 (name, "warn", "From `twisted.logger`."),130 (name, "error", "From `twisted.logger`."),131 (name, "warn", "From `logging`."),132 (name, "error", "From `logging`."),133 ("maas." + name, "warn", "From `get_maas_logger`."),134 ("maas." + name, "error", "From `get_maas_logger`."),135 ("stderr", "error", "Printing to stderr."),136 ("-", "warn", "UserWarning: This is a warning!"),137 ]138 self.assertSequenceEqual(expected, observed)139 def test_twistd_lowest_verbosity(self):140 verbosity, set_verbosity = self._get_log_levels(0)141 name = factory.make_name("log.name")142 logged = log_something(143 name,144 verbosity=verbosity,145 set_verbosity=set_verbosity,146 mode=LoggingMode.TWISTD,147 )148 self.addDetail("logged", text_content(logged))149 observed = find_log_lines(logged)150 expected = [151 (name, "error", "From `twisted.logger`."),152 (name, "error", "From `logging`."),153 ("maas." + name, "error", "From `get_maas_logger`."),154 ("stderr", "error", "Printing to stderr."),155 ]156 self.assertSequenceEqual(expected, observed)157 def test_command_default_verbosity(self):158 verbosity, set_verbosity = self._get_log_levels(2)159 name = factory.make_name("log.name")160 logged = log_something(161 name,162 verbosity=verbosity,163 set_verbosity=set_verbosity,164 mode=LoggingMode.COMMAND,165 )166 self.addDetail("logged", text_content(logged))167 observed = find_log_lines(logged)168 expected = [169 (name, "info", "From `twisted.logger`."),170 (name, "warn", "From `twisted.logger`."),171 (name, "error", "From `twisted.logger`."),172 (name, "info", "From `twisted.python.log`."),173 ("logsomething", "info", "From `twisted.python.log.logfile`."),174 (name, "info", "From `logging`."),175 (name, "warn", "From `logging`."),176 (name, "error", "From `logging`."),177 ("maas." + name, "info", "From `get_maas_logger`."),178 ("maas." + name, "warn", "From `get_maas_logger`."),179 ("maas." + name, "error", "From `get_maas_logger`."),180 ]181 self.assertSequenceEqual(expected, observed)182 self.assertThat(183 logged,184 DocTestMatches(185 """\186 ...187 Printing to stdout.188 Printing to stderr.189 This is a warning!190 """191 ),192 )193 def test_command_high_verbosity(self):194 verbosity, set_verbosity = self._get_log_levels(3)195 name = factory.make_name("log.name")196 logged = log_something(197 name,198 verbosity=verbosity,199 set_verbosity=set_verbosity,200 mode=LoggingMode.COMMAND,201 )202 self.addDetail("logged", text_content(logged))203 observed = find_log_lines(logged)204 expected = [205 (name, "debug", "From `twisted.logger`."),206 (name, "info", "From `twisted.logger`."),207 (name, "warn", "From `twisted.logger`."),208 (name, "error", "From `twisted.logger`."),209 (name, "info", "From `twisted.python.log`."),210 ("logsomething", "info", "From `twisted.python.log.logfile`."),211 (name, "debug", "From `logging`."),212 (name, "info", "From `logging`."),213 (name, "warn", "From `logging`."),214 (name, "error", "From `logging`."),215 ("maas." + name, "debug", "From `get_maas_logger`."),216 ("maas." + name, "info", "From `get_maas_logger`."),217 ("maas." + name, "warn", "From `get_maas_logger`."),218 ("maas." + name, "error", "From `get_maas_logger`."),219 ]220 self.assertSequenceEqual(expected, observed)221 self.assertThat(222 logged,223 DocTestMatches(224 """\225 ...226 Printing to stdout.227 Printing to stderr.228 This is a warning!229 """230 ),231 )232 def test_command_low_verbosity(self):233 verbosity, set_verbosity = self._get_log_levels(1)234 name = factory.make_name("log.name")235 logged = log_something(236 name,237 verbosity=verbosity,238 set_verbosity=set_verbosity,239 mode=LoggingMode.COMMAND,240 )241 self.addDetail("logged", text_content(logged))242 observed = find_log_lines(logged)243 expected = [244 (name, "warn", "From `twisted.logger`."),245 (name, "error", "From `twisted.logger`."),246 (name, "warn", "From `logging`."),247 (name, "error", "From `logging`."),248 ("maas." + name, "warn", "From `get_maas_logger`."),249 ("maas." + name, "error", "From `get_maas_logger`."),250 ]251 self.assertSequenceEqual(expected, observed)252 self.assertThat(253 logged,254 DocTestMatches(255 """\256 ...257 Printing to stdout.258 Printing to stderr.259 This is a warning!260 """261 ),262 )263 def test_command_lowest_verbosity(self):264 verbosity, set_verbosity = self._get_log_levels(0)265 name = factory.make_name("log.name")266 logged = log_something(267 name,268 verbosity=verbosity,269 set_verbosity=set_verbosity,270 mode=LoggingMode.COMMAND,271 )272 self.addDetail("logged", text_content(logged))273 observed = find_log_lines(logged)274 expected = [275 (name, "error", "From `twisted.logger`."),276 (name, "error", "From `logging`."),277 ("maas." + name, "error", "From `get_maas_logger`."),278 ]279 self.assertSequenceEqual(expected, observed)280 self.assertThat(281 logged,282 DocTestMatches(283 """\284 ...285 Printing to stdout.286 Printing to stderr.287 This is a warning!288 """289 ),...
test_logs.py
Source:test_logs.py
1"""Tests that performance data is successfully logged."""2import datetime3import dateutil4import json5import mock6import unittest7import logging8from StringIO import StringIO9from django.test import TestCase10from django.test.client import RequestFactory11from performance.views import performance_log12class PerformanceTrackingTest(TestCase):13 """14 Tests that performance logs correctly handle events15 """16 def setUp(self):17 super(PerformanceTrackingTest, self).setUp()18 self.request_factory = RequestFactory()19 self.stream = StringIO()20 self.handler = logging.StreamHandler(self.stream)21 self.log = logging.getLogger()22 self.log.setLevel(logging.INFO)23 for handler in self.log.handlers:24 self.log.removeHandler(handler)25 self.log.addHandler(self.handler)26 self.addCleanup(self.log.removeHandler, self.handler)27 self.addCleanup(self.handler.close)28 def test_empty_get(self):29 request = self.request_factory.get('/performance')30 pre_time = datetime.datetime.utcnow()31 performance_log(request)32 post_time = datetime.datetime.utcnow()33 self.handler.flush()34 logged_value = json.loads(self.stream.getvalue().strip())35 self.assertEqual(logged_value['accept_language'], '')36 self.assertEqual(logged_value['agent'], '')37 self.assertEqual(logged_value['event'], '')38 self.assertEqual(logged_value['event_source'], 'browser')39 self.assertEqual(logged_value['expgroup'], '')40 self.assertEqual(logged_value['id'], '')41 self.assertEqual(logged_value['page'], '')42 self.assertEqual(logged_value['referer'], '')43 self.assertEqual(logged_value['value'], '')44 logged_time = dateutil.parser.parse(logged_value['time']).replace(tzinfo=None)45 self.assertTrue(pre_time <= logged_time)46 self.assertTrue(post_time >= logged_time)47 def test_empty_post(self):48 request = self.request_factory.post('/performance')49 pre_time = datetime.datetime.utcnow()50 performance_log(request)51 post_time = datetime.datetime.utcnow()52 self.handler.flush()53 logged_value = json.loads(self.stream.getvalue().strip())54 self.assertEqual(logged_value['accept_language'], '')55 self.assertEqual(logged_value['agent'], '')56 self.assertEqual(logged_value['event'], '')57 self.assertEqual(logged_value['event_source'], 'browser')58 self.assertEqual(logged_value['expgroup'], '')59 self.assertEqual(logged_value['id'], '')60 self.assertEqual(logged_value['page'], '')61 self.assertEqual(logged_value['referer'], '')62 self.assertEqual(logged_value['value'], '')63 logged_time = dateutil.parser.parse(logged_value['time']).replace(tzinfo=None)64 self.assertTrue(pre_time <= logged_time)65 self.assertTrue(post_time >= logged_time)66 def test_populated_get(self):67 request = self.request_factory.get('/performance',68 {'event': "a_great_event",69 'id': "12345012345",70 'expgroup': "17", 'page': "atestpage",71 'value': "100234"})72 request.META['HTTP_ACCEPT_LANGUAGE'] = "en"73 request.META['HTTP_REFERER'] = "https://www.edx.org/evilpage"74 request.META['HTTP_USER_AGENT'] = "Mozilla/5.0"75 request.META['REMOTE_ADDR'] = "18.19.20.21"76 request.META['SERVER_NAME'] = "some-aws-server"77 pre_time = datetime.datetime.utcnow()78 performance_log(request)79 post_time = datetime.datetime.utcnow()80 self.handler.flush()81 logged_value = json.loads(self.stream.getvalue().strip())82 self.assertEqual(logged_value['accept_language'], 'en')83 self.assertEqual(logged_value['agent'], 'Mozilla/5.0')84 self.assertEqual(logged_value['event'], 'a_great_event')85 self.assertEqual(logged_value['event_source'], 'browser')86 self.assertEqual(logged_value['expgroup'], '17')87 self.assertEqual(logged_value['host'], 'some-aws-server')88 self.assertEqual(logged_value['id'], '12345012345')89 self.assertEqual(logged_value['ip'], '18.19.20.21')90 self.assertEqual(logged_value['page'], 'atestpage')91 self.assertEqual(logged_value['referer'], 'https://www.edx.org/evilpage')92 self.assertEqual(logged_value['value'], '100234')93 logged_time = dateutil.parser.parse(logged_value['time']).replace(tzinfo=None)94 self.assertTrue(pre_time <= logged_time)95 self.assertTrue(post_time >= logged_time)96 def test_populated_post(self):97 request = self.request_factory.post('/performance',98 {'event': "a_great_event",99 'id': "12345012345",100 'expgroup': "17", 'page': "atestpage",101 'value': "100234"})102 request.META['HTTP_ACCEPT_LANGUAGE'] = "en"103 request.META['HTTP_REFERER'] = "https://www.edx.org/evilpage"104 request.META['HTTP_USER_AGENT'] = "Mozilla/5.0"105 request.META['REMOTE_ADDR'] = "18.19.20.21"106 request.META['SERVER_NAME'] = "some-aws-server"107 pre_time = datetime.datetime.utcnow()108 performance_log(request)109 post_time = datetime.datetime.utcnow()110 self.handler.flush()111 logged_value = json.loads(self.stream.getvalue().strip())112 self.assertEqual(logged_value['accept_language'], 'en')113 self.assertEqual(logged_value['agent'], 'Mozilla/5.0')114 self.assertEqual(logged_value['event'], 'a_great_event')115 self.assertEqual(logged_value['event_source'], 'browser')116 self.assertEqual(logged_value['expgroup'], '17')117 self.assertEqual(logged_value['host'], 'some-aws-server')118 self.assertEqual(logged_value['id'], '12345012345')119 self.assertEqual(logged_value['ip'], '18.19.20.21')120 self.assertEqual(logged_value['page'], 'atestpage')121 self.assertEqual(logged_value['referer'], 'https://www.edx.org/evilpage')122 self.assertEqual(logged_value['value'], '100234')123 logged_time = dateutil.parser.parse(logged_value['time']).replace(tzinfo=None)124 self.assertTrue(pre_time <= logged_time)...
test_signals.py
Source:test_signals.py
1from django.apps import apps2from django.contrib.auth import authenticate, signals3from django.contrib.auth.models import User4from django.core.exceptions import FieldDoesNotExist5from django.test import TestCase, override_settings6from django.test.client import RequestFactory7from .models import MinimalUser, UserWithDisabledLastLoginField8@override_settings(ROOT_URLCONF='auth_tests.urls')9class SignalTestCase(TestCase):10 @classmethod11 def setUpTestData(cls):12 cls.u1 = User.objects.create_user(username='testclient', password='password')13 cls.u3 = User.objects.create_user(username='staff', password='password')14 def listener_login(self, user, **kwargs):15 self.logged_in.append(user)16 def listener_logout(self, user, **kwargs):17 self.logged_out.append(user)18 def listener_login_failed(self, sender, **kwargs):19 self.login_failed.append(kwargs)20 def setUp(self):21 """Set up the listeners and reset the logged in/logged out counters"""22 self.logged_in = []23 self.logged_out = []24 self.login_failed = []25 signals.user_logged_in.connect(self.listener_login)26 signals.user_logged_out.connect(self.listener_logout)27 signals.user_login_failed.connect(self.listener_login_failed)28 def tearDown(self):29 """Disconnect the listeners"""30 signals.user_logged_in.disconnect(self.listener_login)31 signals.user_logged_out.disconnect(self.listener_logout)32 signals.user_login_failed.disconnect(self.listener_login_failed)33 def test_login(self):34 # Only a successful login will trigger the success signal.35 self.client.login(username='testclient', password='bad')36 self.assertEqual(len(self.logged_in), 0)37 self.assertEqual(len(self.login_failed), 1)38 self.assertEqual(self.login_failed[0]['credentials']['username'], 'testclient')39 # verify the password is cleansed40 self.assertIn('***', self.login_failed[0]['credentials']['password'])41 self.assertIn('request', self.login_failed[0])42 # Like this:43 self.client.login(username='testclient', password='password')44 self.assertEqual(len(self.logged_in), 1)45 self.assertEqual(self.logged_in[0].username, 'testclient')46 # Ensure there were no more failures.47 self.assertEqual(len(self.login_failed), 1)48 def test_logout_anonymous(self):49 # The log_out function will still trigger the signal for anonymous50 # users.51 self.client.get('/logout/next_page/')52 self.assertEqual(len(self.logged_out), 1)53 self.assertIsNone(self.logged_out[0])54 def test_logout(self):55 self.client.login(username='testclient', password='password')56 self.client.get('/logout/next_page/')57 self.assertEqual(len(self.logged_out), 1)58 self.assertEqual(self.logged_out[0].username, 'testclient')59 def test_update_last_login(self):60 """Only `last_login` is updated in `update_last_login`"""61 user = self.u362 old_last_login = user.last_login63 user.username = "This username shouldn't get saved"64 request = RequestFactory().get('/login')65 signals.user_logged_in.send(sender=user.__class__, request=request, user=user)66 user = User.objects.get(pk=user.pk)67 self.assertEqual(user.username, 'staff')68 self.assertNotEqual(user.last_login, old_last_login)69 def test_failed_login_without_request(self):70 authenticate(username='testclient', password='bad')71 self.assertIsNone(self.login_failed[0]['request'])72 def test_login_with_custom_user_without_last_login_field(self):73 """74 The user_logged_in signal is only registered if the user model has a75 last_login field.76 """77 last_login_receivers = signals.user_logged_in.receivers78 try:79 signals.user_logged_in.receivers = []80 with self.assertRaises(FieldDoesNotExist):81 MinimalUser._meta.get_field('last_login')82 with self.settings(AUTH_USER_MODEL='auth_tests.MinimalUser'):83 apps.get_app_config('auth').ready()84 self.assertEqual(signals.user_logged_in.receivers, [])85 # last_login is a property whose value is None.86 self.assertIsNone(UserWithDisabledLastLoginField().last_login)87 with self.settings(AUTH_USER_MODEL='auth_tests.UserWithDisabledLastLoginField'):88 apps.get_app_config('auth').ready()89 self.assertEqual(signals.user_logged_in.receivers, [])90 with self.settings(AUTH_USER_MODEL='auth.User'):91 apps.get_app_config('auth').ready()92 self.assertEqual(len(signals.user_logged_in.receivers), 1)93 finally:...
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!!