def test_sms_send4(session, guest_logged): """Test sms_send view by calling with same phone/device more than bi-hourly limit """ site1 = Wifisite.query.filter_by(unifi_id="site1").first() guest_track = Guesttrack.query.first() guest_device = Device.query.first() msg = {"status": 1, "msg": "Code has been send to the mobile"} url = url_for("guest.sms_send", track_id=guest_track.track_id) result = current_app.test_client().post(url, follow_redirects=True, data={"phonenumber": "+123456780"}) assert msg == result.json, "Found msg :%s instead of :%s while trying to send SMS" % (result.json, msg) # fake limit over smsdata = Smsdata.query.first() smsdata.send_try = 6 db.session.commit() result = current_app.test_client().post(url, follow_redirects=True, data={"phonenumber": "+123456780"}) wait_msg = "Looks like SMS network is having issues,please wait for" assert wait_msg in result.json["msg"], "Found msg :%s instead of :%s while trying to send SMS" % ( result.json["msg"], wait_msg, ) # recovering after 2hrs smsdata.timestamp = arrow.utcnow().replace(hours=-2).naive db.session.commit() result = current_app.test_client().post(url, follow_redirects=True, data={"phonenumber": "+123456780"}) assert msg == result.json, "Found msg :%s instead of :%s while trying to send SMS" % (result.json, msg) assert 1 == Smsdata.query.first().send_try, "Smsdata.send_try is not resetting after 2 hrs"
def test_user(self): test_user = User.query.filter_by(userName='******').first() user_info = test_user.to_json() for i in list(user_info.keys()): user_info[i] = str(user_info[i]) user_info['token'] = test_user.generate_auth_token(3600 * 24 * 30) response = current_app.test_client().post( url_for('api.query_by_id', id=test_user.id),\ headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, \ data=json.dumps(user_info) ) # response code 400 self.assertEqual(200, response.status_code) response2 = current_app.test_client().get( url_for('api.get_user_activities',id=test_user.id), ) self.assertEqual(200,response2.status_code) apply_info = { "id":1, "content": "", "token": user_info['token'] } response3 = current_app.test_client().post( url_for('api.user_apply',id=test_user.id), headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, data=json.dumps(apply_info) ) self.assertEqual(200,response3.status_code) response4 = current_app.test_client().get( url_for('api.get_user_messages',id=test_user.id), ) self.assertEqual(200,response4.status_code)
def test_sms_send3(session, guest_logged): """Test sms_send view by calling with same phone/device multiple times """ site1 = Wifisite.query.filter_by(unifi_id="site1").first() guest_track = Guesttrack.query.first() guest_device = Device.query.first() msg = {"status": 1, "msg": "Code has been send to the mobile"} url = url_for("guest.sms_send", track_id=guest_track.track_id) result = current_app.test_client().post(url, follow_redirects=True, data={"phonenumber": "+123456780"}) assert msg == result.json, "Found msg :%s instead of :%s while trying to send SMS" % (result.json, msg) # immediate calling without delay msg_wait = {"status": 0, "msg": "Wait for atleast 30sec before trying again"} result = current_app.test_client().post(url, follow_redirects=True, data={"phonenumber": "+123456780"}) assert msg_wait == result.json, "Found msg :%s instead of :%s while trying to send SMS" % (result.json, msg_wait) # fake 30sec over smsdata = Smsdata.query.first() smsdata.timestamp = arrow.utcnow().replace(seconds=-31).naive db.session.commit() result = current_app.test_client().post(url, follow_redirects=True, data={"phonenumber": "+123456780"}) assert msg == result.json, "Found msg :%s instead of :%s while trying to send SMS" % (result.json, msg) assert 1 == Smsdata.query.count(), "Smsdata is not created even after providing valid phonenumber" assert 2 == Smsdata.query.first().send_try, "Smsdata.send_try is not increamented after two trials"
def test_invite_collaborator(self): video = Video.query.get(1) token = self._send_collaborator_token(video) # Check that collaborator can access video with token with current_app.test_client() as client: r = client.post('/api/validate_token', data=dict(token=token)) self.assertEquals(r.status_code, 200) self.assertEquals(r.json()['display_name'], 'test') with patch('wonder.romeo.core.dolly.DollyUser.get_userdata') as get_userdata: get_userdata.return_value = dict( display_name='test', description='', avatar_thumbnail_url='', profile_cover_url='', ) r = client.get('/api/video/%d' % video.id) self.assertEquals(r.status_code, 200) self.assertEquals(r.json()['account']['name'], 'account1') # Same request for anonymous should fail with current_app.test_client() as client: r = client.get('/api/video/%d' % video.id) self.assertEquals(r.status_code, 401)
def test_mess(self): test_user = User.query.filter_by(userName='******').first() test_activity = Activity.query.filter_by(AID='998').first() test_ua = UserActivity(user=test_user, applyTime='2017-04-09', content="test ua", activity=test_activity, type='applied') test_mess = Message(user=test_user, activity=test_activity, content="test message", time='2017-04-09', isRead=False) db.session.add_all([test_mess, test_ua]) db.session.commit() mess_info = {"token": test_user.generate_auth_token(expiration=3600 * 24 * 30)} response = current_app.test_client().post( url_for('api.change_message_isread', id=test_mess.id), headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, data=json.dumps(mess_info)) self.assertEqual(200, response.status_code) response = current_app.test_client().post( url_for('api.delete_message', id=test_mess.id), headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, data=json.dumps(mess_info)) self.assertIsNone(Message.query.filter_by(content="test message").first()) self.assertEqual(200, response.status_code) Message.query.filter_by(content="test message").delete() UserActivity.query.filter_by(content="test ua").delete() db.session.commit()
def test_guest_session_bypass_auth1(session): '''User who have visited couple of times during the session, visits again after session expiry ''' device_mac = '00:de:ad:be:ef:ca' ap_mac = '00:22:00:00:00:01' site = Wifisite.query.filter_by(unifi_id='site2').first() assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status ##-------------Expire the current session for this user------------------------------------------- gsession = Guestsession.query.filter( and_(Guestsession.mac==device_mac,Guestsession.site_id==site.id)).first() gsession.state = SESSION_EXPIRED session.commit() assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status num_guesttrack = Guesttrack.query.filter( and_(Guesttrack.site_id==site.id)).count() num_session = Guestsession.query.filter( and_(Guestsession.site_id==site.id)).count() num_device = Device.query.filter( and_(Device.site_id==site.id)).count() num_guest = Guest.query.filter( and_(Guest.site_id==site.id)).count() assert num_guesttrack == 5 ,"Guesttrack entries not equal to the number of visits:%s"%num_guesttrack assert num_session == 2 ,"Guestsession entries not equal to the number of sessions" assert num_device == 1 ,"Device entries not equal to the number of unique Devices" assert num_guest == 1 ,"Guest entries not equal to the number of unique Devices"
def test_email_login1(session): '''Email login with invalid parameters and authorized device ''' device_mac = '00:de:ad:be:ef:da' ap_mac = '00:22:00:00:00:01' site = Wifisite.query.filter_by(unifi_id='site3').first() #invalid track ID assert '404 NOT FOUND' == current_app.test_client().get('/guest/email/guest/67yte7ey51wy167w2816i2351835').status #test valid trackid but no session track_id = str(uuid.uuid4()) guest_track = Guesttrack(ap_mac=ap_mac,device_mac=device_mac,site=site,state=GUESTRACK_INIT,orig_url='',track_id=track_id) session.add(guest_track) session.commit() assert '404 NOT FOUND' == current_app.test_client().get('/guest/email/check/%s'%track_id).status #create session but no device guest_session = Guestsession(mac=device_mac,state=SESSION_INIT,site=site) session.add(guest_session) site.sessions.append(guest_session) guest_track.session = guest_session guest_session.guesttracks.append(guest_track) guest_track.state = GUESTRACK_SESSION session.commit() assert '404 NOT FOUND' == current_app.test_client().get('/guest/email/guest/%s'%track_id).status #with session and authorized device guest_device = Device(mac=device_mac,site=site,state=DEVICE_AUTH) site.devices.append(guest_device) session.add(guest_device) guest_device.sessions.append(guest_session) session.commit() assert '/guest/auth/guest/%s'%track_id in current_app.test_client().get('/guest/email/guest/%s'%track_id).data assert guest_session.state == SESSION_AUTHORIZED assert guest_track.state == GUESTRACK_SOCIAL_PREAUTH
def test_sms_send3(session,guest_logged): '''Test sms_send view by calling with same phone/device multiple times ''' site1 = Wifisite.query.filter_by(unifi_id='site1').first() guest_track = Guesttrack.query.first() guest_device = Device.query.first() msg= {'status':1,'msg':"Code has been send to the mobile"} url = url_for('guest.sms_send',track_id=guest_track.track_id) result = current_app.test_client().post(url,follow_redirects=True,data={'phonenumber':'+123456780'}) assert msg == result.json ,\ 'Found msg :%s instead of :%s while trying to send SMS'%(result.json,msg) #immediate calling without delay msg_wait = {'status':0,'msg':"Wait for atleast 30sec before trying again"} result = current_app.test_client().post(url,follow_redirects=True,data={'phonenumber':'+123456780'}) assert msg_wait == result.json ,\ 'Found msg :%s instead of :%s while trying to send SMS'%(result.json,msg_wait) #fake 30sec over smsdata = Smsdata.query.first() smsdata.timestamp = arrow.utcnow().replace(seconds=-31).naive db.session.commit() result = current_app.test_client().post(url,follow_redirects=True,data={'phonenumber':'+123456780'}) assert msg == result.json ,\ 'Found msg :%s instead of :%s while trying to send SMS'%(result.json,msg) assert 1 == Smsdata.query.count() , "Smsdata is not created even after providing valid phonenumber" assert 2 == Smsdata.query.first().send_try , "Smsdata.send_try is not increamented after two trials"
def test_register(self): if IntroCode.query.filter_by(code="12345678").first() is None: new_intro_code = IntroCode(code="12345678") db.session.add(new_intro_code) db.session.commit() self.assertIsNotNone(IntroCode.query.filter_by(code="12345678").first()) data = {"introcode": "12345678", "email": "test@register", "username": "******", "password": "******","password2":"test_user_pw"} response = current_app.test_client().post( url_for('auth.register'), data=data ) json_data = response.data time.sleep(2) new_team = Team.query.filter_by(email="test@register").first() self.assertIsNotNone(new_team) response = current_app.test_client().get(url_for('auth.logout')) self.assertIsNotNone(response) Team.query.filter_by(email="test@register").delete() IntroCode.query.filter_by(code="12345678").delete() db.session.commit()
def test_facebook_login1(session): '''Facebook login with invalid parameters and no fb cookies ''' device_mac = '00:de:ad:be:ef:da' ap_mac = '00:22:00:00:00:01' site = Wifisite.query.filter_by(unifi_id='site1').first() #invalid track ID assert '404 NOT FOUND' == current_app.test_client().get('/guest/facebook/check/67yte7ey51wy167w2816i2351835').status #test valid trackid but no session track_id = str(uuid.uuid4()) guest_track = Guesttrack(ap_mac=ap_mac,device_mac=device_mac,site=site,state=GUESTRACK_INIT,orig_url='',track_id=track_id) db.session.add(guest_track) db.session.commit() assert '404 NOT FOUND' == current_app.test_client().get('/guest/facebook/check/%s'%track_id).status #create session but no device guest_session = Guestsession(mac=device_mac,state=SESSION_INIT,site=site) db.session.add(guest_session) site.sessions.append(guest_session) guest_track.session = guest_session guest_session.guesttracks.append(guest_track) guest_track.state = GUESTRACK_SESSION db.session.commit() assert '404 NOT FOUND' == current_app.test_client().get('/guest/facebook/check/%s'%track_id).status #with session and authorized device guest_device = Device(mac=device_mac,site=site,state=DEVICE_INIT) site.devices.append(guest_device) db.session.add(guest_device) guest_device.sessions.append(guest_session) db.session.commit()
def test_sms_send4(session,guest_logged): '''Test sms_send view by calling with same phone/device more than bi-hourly limit ''' site1 = Wifisite.query.filter_by(unifi_id='site1').first() guest_track = Guesttrack.query.first() guest_device = Device.query.first() msg= {'status':1,'msg':"Code has been send to the mobile"} url = url_for('guest.sms_send',track_id=guest_track.track_id) result = current_app.test_client().post(url,follow_redirects=True,data={'phonenumber':'+123456780'}) assert msg == result.json ,\ 'Found msg :%s instead of :%s while trying to send SMS'%(result.json,msg) #fake limit over smsdata = Smsdata.query.first() smsdata.send_try = 6 db.session.commit() result = current_app.test_client().post(url,follow_redirects=True,data={'phonenumber':'+123456780'}) wait_msg = 'Looks like SMS network is having issues,please wait for' assert wait_msg in result.json['msg'] ,\ 'Found msg :%s instead of :%s while trying to send SMS'%(result.json['msg'],wait_msg) #recovering after 2hrs smsdata.timestamp = arrow.utcnow().replace(hours=-2).naive db.session.commit() result = current_app.test_client().post(url,follow_redirects=True,data={'phonenumber':'+123456780'}) assert msg == result.json ,\ 'Found msg :%s instead of :%s while trying to send SMS'%(result.json,msg) assert 1 == Smsdata.query.first().send_try , "Smsdata.send_try is not resetting after 2 hrs"
def test_social_login(session): '''User who have visited couple of times during the session, visits again after session expiry ''' device_mac = '00:de:ad:be:ef:ca' ap_mac = '00:22:00:00:00:01' site = Wifisite.query.filter_by(unifi_id='site2').first() assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status ##-------------Expire the current session for this user------------------------------------------- gsession = Guestsession.query.filter( and_(Guestsession.mac==device_mac,Guestsession.site_id==site.id)).first() gsession.state = SESSION_EXPIRED session.commit() assert '302 FOUND' == current_app.test_client().get('/guest/s/site2/?id=00:de:ad:be:ef:ca&ap=00:22:00:00:00:01').status num_guesttrack = Guesttrack.query.filter( and_(Guesttrack.site_id==site.id)).count() num_session = Guestsession.query.filter( and_(Guestsession.site_id==site.id)).count() num_device = Device.query.filter( and_(Device.site_id==site.id)).count() num_guest = Guest.query.filter( and_(Guest.site_id==site.id)).count() assert num_guesttrack == 5 ,"Guesttrack entries not equal to the number of visits:%s"%num_guesttrack assert num_session == 2 ,"Guestsession entries not equal to the number of sessions" assert num_device == 1 ,"Device entries not equal to the number of unique Devices" assert num_guest == 1 ,"Guest entries not equal to the number of unique Devices"
def test_guest_invalid_values(session): # print "sleep 20" #test for all parameters (id and ap_mac) given by coming user assert '404 NOT FOUND' == current_app.test_client().get('/guest/s/site1/').status assert '404 NOT FOUND' == current_app.test_client().get('/guest/s/site1/?ap=00:01:00:00:00:11').status assert '404 NOT FOUND' == current_app.test_client().get('/guest/s/site1/?id=00:de:ad:be:ef:ca').status assert '404 NOT FOUND' == current_app.test_client().get('/guest/s/error/?id=00:de:ad:be:ef:ca&ap=00:01:00:00:00:11').status
def test_sync_unhandled_exception(): old_throttle = pypi.THROTTLE pypi.THROTTLE = 'nan' redis.delete(POLL_SIMPLE_THROTTLE) with pytest.raises(ValueError): current_app.test_client().get('/pypi/sync').status() pypi.THROTTLE = old_throttle
def setUp(self): self.app = current_app.test_client(); self.requestHelper = RequestsHelper(current_app.test_client(), 'api/patients') service = Service(name='service api', price='1500') service2 = Service(name='service api2', price='1200') service3 = Service(name='service api3', price='3520') db.session.add(service) db.session.add(service2) db.session.add(service3) db.session.commit()
def setUp(self): self.app = current_app.test_client(); self.requestHelper = RequestsHelper(current_app.test_client(), 'api/users') user = User(password='******', name='user api', userName='******') user2 = User(password='******', name='user api2', userName='******') user3 = User(password='******', name='user api3', userName='******') db.session.add(user) db.session.add(user2) db.session.add(user3) db.session.commit()
def setUp(self): self.app = current_app.test_client(); self.requestHelper = RequestsHelper(current_app.test_client(), 'api/rooms') room = Room(name='room api') room2 = Room(name='room api2') room3 = Room(name='room api3') db.session.add(room) db.session.add(room2) db.session.add(room3) db.session.commit()
def test_guest_invalid_values(session): # print "sleep 20" #test for all parameters (id and ap_mac) given by coming user assert '404 NOT FOUND' == current_app.test_client().get( '/guest/s/site1/').status assert '404 NOT FOUND' == current_app.test_client().get( '/guest/s/site1/?ap=00:01:00:00:00:11').status assert '404 NOT FOUND' == current_app.test_client().get( '/guest/s/site1/?id=00:de:ad:be:ef:ca').status assert '404 NOT FOUND' == current_app.test_client().get( '/guest/s/error/?id=00:de:ad:be:ef:ca&ap=00:01:00:00:00:11').status
def setUp(self): self.app = current_app.test_client(); self.requestHelper = RequestsHelper(current_app.test_client(), 'api/patients') patient = Patient(name='patient api', mobileNumber='11111111111') patient2 = Patient(name='patient api2', mobileNumber='121212211212') patient3 = Patient(name='patient api3', mobileNumber='3223232323') db.session.add(patient) db.session.add(patient2) db.session.add(patient3) db.session.commit() pass
def setUp(self): self.app = current_app.test_client() self.requestHelper = RequestsHelper(current_app.test_client(), "api/patients") patient = Patient(name="patient api", mobileNumber="11111111111") patient2 = Patient(name="patient api2", mobileNumber="121212211212") patient3 = Patient(name="patient api3", mobileNumber="3223232323") db.session.add(patient) db.session.add(patient2) db.session.add(patient3) db.session.commit() pass
def setUp(self): self.repo = self.create_repo( url='https://github.com/dropbox/changes.git', ) self.project = self.create_project( repository=self.repo, name='test', slug='test' ) self.project2 = self.create_project( repository=self.repo, name='test2', slug='test2', ) self.plan = self.create_plan() self.plan.projects.append(self.project) db.session.commit() # mock out mail mail_context = mail.record_messages() self.outbox = mail_context.__enter__() self.addCleanup(lambda: mail_context.__exit__(None, None, None)) self.client = app.test_client() super(TestCase, self).setUp()
def setUp(self): db.create_all() for datum in good_data: asset = Asset(**datum) db.session.add(asset) db.session.commit() self.client = current_app.test_client()
def http_call(self, url, method, **kwargs): """Fakes a http call through Flask/Werkzeug.""" client = current_app.test_client() self.requests_to_flask_kwargs(kwargs) # Leave out the query string and fragment from the URL. split_url = urllib.parse.urlsplit(url) path = urllib.parse.urlunsplit(split_url[:-2] + (None, None)) try: response = client.open(path=path, query_string=split_url.query, method=method, **kwargs) except Exception as ex: log.warning('Error performing HTTP %s request to %s: %s', method, url, str(ex)) raise if method == 'OPTIONS': return response self.flask_to_requests_response(response) try: content = self.handle_response(response, response.data) except: log.warning("%s: Response[%s]: %s", url, response.status_code, response.data) raise return content
def datapackage_show(owner, id): """ Loads datapackage page for given owner --- tags: - site parameters: - name: owner in: path type: string required: true description: datapackage owner name - name: id in: path type: string description: datapackage name responses: 404: description: Datapackage does not exist 200: description: Succesfuly loaded """ metadata = json.loads(app.test_client().get('/api/{owner}/{id}'.format( owner=owner, id=id)).data) if metadata['status'] == 'KO': return "404 Not Found", 404 dataset = metadata['data'] resources = dataset['resources'] dataViews = dataset['views'] or [] return render_template("dataset.html", dataset=dataset, showDataApi=True, jsonDataPackage=dataset, dataViews=dataViews), 200
def _write_loaded_data(self): client = current_app.test_client() url = "/api/slicer/cube/geometry/cubes_aggregate?cubes=" + self.dataset.name + "&drilldown=geometry__time|geometry__country_level0@name&format=csv" with client: # Fill in your details here to be posted to the login form. LOCKDOWN_FORCE = current_app.config.get("LOCKDOWN_FORCE", False) LOCKDOWNUSER = current_app.config.get("LOCKDOWNUSER") LOCKDOWNPASSWORD = current_app.config.get("LOCKDOWNPASSWORD") if LOCKDOWN_FORCE: payload = { 'username': LOCKDOWNUSER, 'password': LOCKDOWNPASSWORD } client.post(url_for('home.lockdown'), data=payload, follow_redirects=True) try: postloadvalue = client.get(url, follow_redirects=True).data except Exception, e: log.warn("Could Not find post load content for " + dataset.name)
def test_authenticate_sms5(session, guest_logged): """Test authenticate_sms view by posting correctly """ site1 = Wifisite.query.filter_by(unifi_id="site1").first() guest_track = Guesttrack.query.first() guest_device = Device.query.first() phonenumber = "+123456789" smsdata = Smsdata(phonenumber=phonenumber, device=guest_device) db.session.add(smsdata) guest_device.smsdatas.append(smsdata) smsdata.authcode = random.randrange(10000, 99999, 1) db.session.commit() url = url_for("guest.authenticate_sms", track_id=guest_track.track_id) result = current_app.test_client().post( url, follow_redirects=False, data={"phonenumber": phonenumber, "authcode": smsdata.authcode} ) auth_url = url_for("guest.multi_login", track_id=guest_track.track_id, _external=True) assert auth_url == result.location, "UE gets redirected to :%s instead of expected :%s" % ( result.location, auth_url, ) assert 1 == guest_device.sms_confirm, "sms_confirm is not set after submit"
def test_add_data(): httpretty.register_uri(httpretty.GET, re.compile('.*/commits'), status=200, body=json.dumps([ { 'author': { 'login': '******' }, 'commit': { 'message': 'New setup.py.' } }, { 'author': { 'login': '******' }, 'commit': { 'message': 'Old setup.py.' } }, ])) httpretty.register_uri(httpretty.GET, re.compile('.*/contributors'), status=200, body='[{"weeks": [{"a": 1}]}]') assert '200 OK' == current_app.test_client().post( '/api/query_github', data=dict(repo_url='1/2')).status expected = [('1/2', 1, 'Myself You', 'New setup.py.')] actual = db.session.query(Repository.url, Repository.line_count, Repository.top_committers, Repository.last_commit).all() assert expected == actual
def test_social_login2(session): '''Social login with unauthorized device ''' device_mac = '00:de:ad:be:ef:ca' ap_mac = '00:22:00:00:00:01' site = Wifisite.query.filter_by(unifi_id='site1').first() #test valid trackid but no session track_id = str(uuid.uuid4()) guest_track = Guesttrack(ap_mac=ap_mac,device_mac=device_mac,site=site,state=GUESTRACK_INIT,orig_url='',track_id=track_id) db.session.add(guest_track) db.session.commit() #create session guest_session = Guestsession(mac=device_mac,state=SESSION_INIT,site=site) db.session.add(guest_session) site.sessions.append(guest_session) guest_track.session = guest_session guest_session.guesttracks.append(guest_track) guest_track.state = GUESTRACK_SESSION db.session.commit() #with session and unauthorized device guest_device = Device(mac=device_mac,site=site,state=DEVICE_INIT) site.devices.append(guest_device) db.session.add(guest_device) guest_device.sessions.append(guest_session) db.session.commit() assert '200 OK' == current_app.test_client().get('/guest/social/guest/%s'%track_id).status assert guest_session.state == SESSION_TEMP_AUTH
def test_social_login2(session): '''Social login with unauthorized device ''' device_mac = '00:de:ad:be:ef:ca' ap_mac = '00:22:00:00:00:01' site = Wifisite.query.filter_by(unifi_id='site1').first() #test valid trackid but no session track_id = str(uuid.uuid4()) guest_track = Guesttrack(ap_mac=ap_mac, device_mac=device_mac, site=site, state=GUESTRACK_INIT, orig_url='', track_id=track_id) db.session.add(guest_track) db.session.commit() #create session guest_session = Guestsession(mac=device_mac, state=SESSION_INIT, site=site) db.session.add(guest_session) site.sessions.append(guest_session) guest_track.session = guest_session guest_session.guesttracks.append(guest_track) guest_track.state = GUESTRACK_SESSION db.session.commit() #with session and unauthorized device guest_device = Device(mac=device_mac, site=site, state=DEVICE_INIT) site.devices.append(guest_device) db.session.add(guest_device) guest_device.sessions.append(guest_session) db.session.commit() assert '200 OK' == current_app.test_client().get('/guest/social/guest/%s' % track_id).status assert guest_session.state == SESSION_TEMP_AUTH
def setUp(self): self.app = create_app('testing') self.ctx = self.app.app_context() self.ctx.push() self.client = current_app.test_client() self.db = db self.db.create_all()
def setUp(self): self.client = current_app.test_client() if not self.gen_data: response = self.client.post( 'http://localhost:5000/api/busers/session', data=json.dumps({ "username": "******", "password": "******", })) self.assertTrue("Successfully login." in response.get_data( as_text=True)) for promotion in self.promotions: response = self.client.post( 'http://localhost:5000/api/promotions/', data=json.dumps(promotion)) # print(response.get_data(as_text=True)) self.assertTrue(response.status_code == 200) response = self.client.post( 'http://localhost:5000/api/promotions/1/rules', data=json.dumps({ 'mode': 1, 'requirement': 100, 'discount': 10 })) self.assertTrue(response.status_code == 200) # 退出 response = self.client.put( 'http://localhost:5000/api/busers/session') self.gen_data = True
def update(key, name, owner, code, private, locked): collection = Collection.objects(key=key).first() old_code = collection.code if name: collection.name = name if owner: collection.owner = owner if code: collection.code = code if private is not None: collection.private = private if locked is not None: collection.locked = locked try: collection.save() except exceptions.NotUniqueError: msg = f"Short code is already taken: {collection.code}" raise exceptions.UnprocessableEntity(msg) except exceptions.ValidationError as exc: msg = list(exc.to_dict().values())[0] raise exceptions.UnprocessableEntity(msg) if old_code and old_code != collection.code: data = {'start_slug': old_code, 'end_slug': collection.code} result = current_app.test_client().post("/api/redirects/", data=data) log.debug(result) return serialize(collection), status.HTTP_200_OK
def create_notification(title, description, user): """Create a new notification""" try: notification = { "title": title, "description": description, "user": user } resp = app.test_client().post('/'+app.config['API_VERSION']+'/notifications/', data=toJSON(notification), content_type='application/json') if int(resp.status_code)/100 == 2: logger.debug("Notification created successfully") else: logger.debug("Notification creation failed") raise Exception("Notification creation failed") except Exception as e: # TODO: handle exceptions logger.error("Error creating notification: " + str(e), exc_info=1) return 1 return 0 # # Execute a function call in thread # def threaded(call, *args, **kwargs): # """Execute ``call(*args, **kwargs)`` in a thread""" # thread = threading.Thread(target=call, args=args, kwargs=kwargs) # thread.start() # return thread # def is_main_thread_active(): # return any((i.name == "MainThread") and i.is_alive() for i in threading.enumerate())
def get_response_from_view(url, auth=None, data=None, as_json=False): # https://stackoverflow.com/a/21342070/10517783 How do I call one Flask view from another one? # https://stackoverflow.com/a/30250045/10517783 # python - Flask test_client() doesn't have request.authorization with pytest client = app.test_client() if auth is not None: headers = {'Authorization': basic_auth_header(*auth)} else: headers = {} if data is not None: response = client.post(url, headers=headers, data=data, content_type='multipart/form-data') else: response = client.get(url, headers=headers) text = response.get_data(as_text=True) if as_json: # e.g. when used in schedule_task() # 'node index error: %s, which should be between 1 and %s' % (self.node, self.SCRAPYD_SERVERS_AMOUNT) # json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) try: return json.loads(text) except ValueError: # '_status': '500 INTERNAL SERVER ERROR', # '_status_code': 500, # See 500.html # <tr><th>Error</th><td>node index error: 2, which should be between 1 and 1</td></tr> # <pre>Traceback...AssertionError: node index error: 2, which should be between 1 and 1 </pre> m = re.search(r'<tr><th>Error</th><td>(.+?)</td></tr>', text, re.S) message = m.group(1) if m else text return dict(status_code=getattr(response, '_status_code', 500), status='error', message=message) else: return text
def check_facebook_login_page(url): ''' Visit the URL and follow directs, and ensure that page returned have FB login form''' result = current_app.test_client().get(url, follow_redirects=True) assert '200 OK' == result.status, 'Current user getting:%s instead of 200 OK while trying to View URL:%s' % ( result.status, url) assert 'Login Using Facebook' in result.data,\ 'Facebook Login button not seen check_facebook_login_page at URL:%s'%(url)
def test_authorize_guest2(session): """ authorize_guest check if parameters are correctly configured """ # create a guest visitor site1 = Wifisite.query.filter_by(id=1).first() mac = randomMAC() ap_mac = randomMAC() site1.auth_method = AUTH_TYPE_SOCIAL + AUTH_TYPE_SMS + AUTH_TYPE_EMAIL + AUTH_TYPE_VOUCHER db.session.commit() url = get_guest_url(site1, mac, ap_mac, demo=0) check_multi_login_page(url) guest_track = Guesttrack.query.first() # authorize session guest_track.state = GUESTRACK_SOCIAL_AUTH auth_url = url_for("guest.authorize_guest", track_id=guest_track.track_id) result = current_app.test_client().get(auth_url, follow_redirects=True) assert "200 OK" == result.status, "authorize_guest getting:%s instead of 200 OK while trying to View URL:%s" % ( result.status, url, ) # check if guest_session is created guest_session = Guestsession.query.first() assert isinstance(guest_session, Guestsession), "Guestsession is not created when calling authorize_guest" assert guest_session.state == GUESTRACK_SOCIAL_AUTH, " guest_session state is not GUESTRACK_SOCIAL_AUTH"
def oembed(url): path = urlparse(url).path + "?format=json" with app.test_client() as c: rv = c.get(path) try: article = loads(rv.data) except ValueError: print url print path raise if request.args.get("format") == "html": return html(article) return { "success": True, "type": "rich", "version": "1.0", "provider_name": "Venturelog", "provider_url": "http://www.venturelog.io", "title": article['headline'], "author_name": "Brad Smith", "author_url": "http://www.venturelog.io", "height": "300", "width": "800", "thumbnail_width": "200", "thumbnail_height": str(int(200 * float(3) / 4)), "thumbnail_url": thumbUrl(article['thumbnail']), "html": html(article) }
def test_voucher_login2(session,create_vouchers,guest_logged): '''Test voucher_login view with pre authorized guest with non expired voucher ''' site1 = Wifisite.query.filter_by(unifi_id='site1').first() guest_track = Guesttrack.query.first() guest_device = Device.query.first() voucher = Voucher.query.first() #device and used voucher used_at = arrow.utcnow().replace(days=2).datetime guest_device.state = DEVICE_VOUCHER_AUTH voucher.device_id = guest_device.id voucher.used = True voucher.used_at = used_at #create a session representing old session guest_session = Guestsession(site=site1,device=guest_device) guest_session.state = GUESTRACK_VOUCHER_AUTH guest_session.mac = guest_device.mac guest_session.guesttracks.append(guest_track) db.session.add(guest_session) guest_track.session_id = guest_session.id #fake variables for session guest_session.starttime = used_at guest_session.lastseen = used_at guest_session.data_used = 500000 db.session.commit() url = url_for('guest.voucher_login',track_id=guest_track.track_id) result = current_app.test_client().post(url,follow_redirects=False) auth_url = url_for('guest.authorize_guest',track_id=guest_track.track_id, _external=True) assert auth_url == result.location, "UE gets redirected to :%s instead of expected :%s"%(result.location,auth_url)
def test_voucher_login5(session,create_vouchers,guest_logged): '''Test voucher_login view by entering voucher ''' site1 = Wifisite.query.filter_by(unifi_id='site1').first() guest_track = Guesttrack.query.first() guest_device = Device.query.first() voucher = Voucher.query.first() url = url_for('guest.voucher_login',track_id=guest_track.track_id) firstname = fake.first_name() lastname = fake.last_name() email = fake.email() form_data = {'firstname':firstname,'email':email,'lastname':lastname,'voucher':voucher.voucher} result = current_app.test_client().post(url,follow_redirects=False,data=form_data) auth_url = url_for('guest.authorize_guest',track_id=guest_track.track_id, _external=True) assert auth_url == result.location, "UE gets redirected to :%s instead of expected :%s"%(result.location,auth_url) #check if guest is created guest = Guest.query.first().to_dict() assert form_data['firstname'] == guest['firstname'],\ 'Guest firstname not matching expected:%s getting:%s'%(form_data['firstname'],guest['firstname']) assert form_data['lastname'] == guest['lastname'],\ 'Guest lastname not matching Expected:%s Got: %s'%(form_data['lastname'],guest['lastname']) assert site1.id == guest['site_id'], "Giest site_id not matching expected:%s got:%s"%(site1.id,guest['site_id']) guest_track = Guesttrack.query.first() assert GUESTRACK_VOUCHER_AUTH == guest_track.state, "Guesttrack state is not GUESTRACK_VOUCHER_AUTH" assert voucher.time_available() == guest_track.duration, "Guesttrack duration is not expected "
def setUp(self): self.db_fd, current_app.config['DATABASE'] = tempfile.mkstemp() current_app.config['TESTING'] = True self.client = current_app.test_client() #db = _get_db() #db.connection.drop_database(current_app.config['MONGODB_SETTINGS']['DB']) loadFixtures()
def test_email_login3(fake_facebook,session,guest_logged): '''Test email_login view with guest enetering data ''' site1 = Wifisite.query.filter_by(unifi_id='site1').first() guest_track = Guesttrack.query.first() guest_device = Device.query.first() url = url_for('guest.email_login',track_id=guest_track.track_id) firstname = fake.first_name() lastname = fake.last_name() email = fake.email() form_data = {'firstname':firstname,'email':email,'lastname':lastname} url = url_for('guest.email_login',track_id=guest_track.track_id) result = current_app.test_client().post(url,follow_redirects=False,data=form_data) auth_url = url_for('guest.authorize_guest',track_id=guest_track.track_id, _external=True) assert auth_url == result.location, "UE gets redirected to :%s instead of expected :%s"%(result.location,auth_url) #check if guest is created guest = Guest.query.first().to_dict() assert form_data['firstname'] == guest['firstname'],\ 'Guest firstname not matching expected:%s getting:%s'%(form_data['firstname'],guest['firstname']) assert form_data['lastname'] == guest['lastname'],\ 'Guest lastname not matching Expected:%s Got: %s'%(form_data['lastname'],guest['lastname']) assert form_data['email'] == guest['email'],\ 'Guest email not matching Expected:%s Got: %s'%(form_data['email'],guest['email']) assert site1.id == guest['site_id'], "Giest site_id not matching expected:%s got:%s"%(site1.id,guest['site_id']) guest_track = Guesttrack.query.first() assert GUESTRACK_EMAIL_AUTH == guest_track.state, "Guesttrack state is not GUESTRACK_EMAIL_AUTH"
def oembed(url): path = urlparse(url).path + "?format=json" with app.test_client() as c: rv = c.get(path) try: article = loads(rv.data) except ValueError: print url print path raise if request.args.get("format") == "html": return html(article) return { "success": True, "type": "rich", "version": "1.0", "provider_name": "Venturelog", "provider_url": "http://www.venturelog.io", "title": article['headline'], "author_name": "Brad Smith", "author_url": "http://www.venturelog.io", "height": "300", "width": "800", "thumbnail_width": "200", "thumbnail_height": str(int(200 * float(3)/4)), "thumbnail_url": thumbUrl(article['thumbnail']), "html": html(article) }
def _make_context(): return dict( db=OrmDb(), repos=repositories, tt=testtools, client=current_app.test_client() )
def app(): # doing tests on remote "not-sqlite" DB, create app wit TestConfig as argument app = create_app(TestConfig) with app.app_context(): current_app.test_client() db.create_all() user1 = User(username="******", email="*****@*****.**") user2 = User(username="******", email="*****@*****.**") user3 = User(username="******", email="*****@*****.**") user3.set_password("micha") user3.encrypt_site_password("MaRaKuJa1") db.session.add_all([user1, user2, user3]) db.session.commit() yield current_app
def admin1_logged(request): '''fixture used to create a logged in instance of test_client based on multiple examples like http://librelist.com/browser/flask/2012/7/1/giving-context-to-test-client/#dfb70ea7e1b300da59d9d0ba6a2c0d52 ''' username = '******' password = '******' original_client = current_app.test_client logged_client = current_app.test_client() login_resp = logged_client.post(url_for('security.login'), data={ 'email': username, 'password': password }, follow_redirects=True) assert 'Bad username or password' not in login_resp.data, 'Login Failed ' current_app.test_client = logged_client #temperarly replace test_client with instance of logged in client def teardown(): current_app.test_client = original_client #change back client to original version request.addfinalizer(teardown) return logged_client
def dispatch( self, path: str, method: str, data: dict = None, files: Mapping[str, BinaryIO] = None, json: dict = None, params: dict = None, request=None, tenant=True, ) -> Response: if request: assert not json assert not data assert not files data = request.data files = request.files json = None params = request.args if tenant is True: tenant = auth.get_current_tenant() if json: assert not data data = dumps(json) content_type = 'application/json' elif files: if not data: data = {} for key, value in request.form.items(): data[key] = value for key, value in files.items(): data[key] = value content_type = 'multipart/form-data' else: content_type = None with current_app.test_client() as client: response = client.open(path='/api/{}'.format(path.lstrip('/')), query_string=params, method=method, content_type=content_type, data=data, environ_overrides={ 'zeus.tenant': tenant, }) if not (200 <= response.status_code < 300): raise ApiError( text=response.get_data(as_text=True), code=response.status_code, ) if response.headers['Content-Type'] != 'application/json': raise ApiError( text='Request returned invalid content type: {}'.format( response.headers['Content-Type']), code=response.status_code, ) return response
def test_sync_rate_limit(alter_xmlrpc): alter_xmlrpc([dict(name='packageC', summary='Test package.', version='3.0.0'), ]) assert '302 FOUND' == current_app.test_client().get('/pypi/sync').status expected = [('packageB', 'Test package.', '3.0.0'), ] actual = db.session.query(Package.name, Package.summary, Package.latest_version).all() assert expected == actual
def test_pretty_page(): with current_app.test_client() as c: c.application.config['PROPAGATE_EXCEPTIONS'] = False request = c.get('/examples/exception/') c.application.config['PROPAGATE_EXCEPTIONS'] = True assert '500 INTERNAL SERVER ERROR' == request.status assert '<title>PyPI Portal - HTTP 500</title>' in request.data
def test_sync_empty(alter_xmlrpc): alter_xmlrpc(set()) redis.delete(POLL_SIMPLE_THROTTLE) Package.query.delete() db.session.commit() assert '302 FOUND' == current_app.test_client().get('/pypi/sync').status assert [] == db.session.query(Package.name, Package.summary, Package.latest_version).all()
def setUp(self): self.app = current_app.test_client() self.requestHelper = RequestsHelper(current_app.test_client(), 'api/service_orders') patient = Patient(name='patient xyz from service order api test ', mobileNumber='54687643756') service = Service(name='service xyz XXX', price=450) db.session.add(patient) db.session.add(service) serviceOrder = ServiceOrder(patient=patient, service=service, numberOfSessions=12) serviceOrder2 = ServiceOrder(patient=patient, service=service, numberOfSessions=4) serviceOrder3 = ServiceOrder(patient=patient, service=service, numberOfSessions=8) db.session.add(serviceOrder) db.session.add(serviceOrder2) db.session.add(serviceOrder3) db.session.commit()
def test_update_settings_fails_when_bad_content_type(self, av_get_settings_document, av_update_generic): av_get_settings_document.return_value = {'starfish': 'patrick'} with current_app.test_client() as c: resp_object = c.put('/api/v1/admin/settings',content_type='spongey') assert resp_object.data == '"no valid settings parameters supplied"' assert resp_object.status_code == 409
def test_wifisite_api2(session): ''' Test Wifisite invalid API calls ''' #Invalid API requests assert '404 NOT FOUND' == current_app.test_client().get('/client/site/api/20').status assert '404 NOT FOUND' == current_app.test_client().post('/client/site/api/20').status assert '404 NOT FOUND' == current_app.test_client().delete('/client/site/api/20').status assert '405 METHOD NOT ALLOWED' == current_app.test_client().delete('/client/site/api/').status #test getting all stored sites result = current_app.test_client().get('/client/site/api/').json assert 1 == result['status'] assert 3 == len(result['data']) assert site1 == result['data'][0] assert site2 == result['data'][1] assert site3 == result['data'][2]
def run(self, result=None): # initialize global test configuration here... global_test_config = {} global_test_config.update(self.custom_test_config or {}) with provision_database(global_test_config): self.client = current_app.test_client() super().run(result)
def start(type): """ Start new node :param type: str - rs | aws[ | regular?] - type of registered node :return: """ nodes = [] # rs | aws if type == 'rs': prop_parent = Property.query.filter_by(name='rs').all() # props_by_user = Property.query.filter(Property.users.contains(current_user)).limit(100).all() print prop_parent, current_user.props # for role in current_user.roles: # print role.id # prop_by_roles = Property.query.filter(Property.roles.contains(role)).all() # for prop in prop_by_roles: # print prop props = {} for p in current_user.props: print p.id props_filter = ['ssh_keys', 'rs_credentials'] for name in props_filter: if p.parent and p.parent.name == name: if not props.get(name): props[name] = {} props[name][p.name] = p.value print props['rs_credentials'] # with current_app.test_request_context('/'): # print current_app.user_datastore # u = current_user api = RsVm.instance(dict=props['rs_credentials']) api.enable_cache_handler(auth_cache_handler) print current_app.test_client() print api._get_config() nodes = api.list_servers().get('servers') return dict(nodes=nodes, exec_url="/exec/123"), 200
def test_get_group_fails_when_group_not_found(self, av_get_group_document, av_get_group_document_with_child_links, av_get_group_document_with_child_objects): av_get_group_document.side_effect = NotFoundError('no group document found for 4422') resp_object = current_app.test_client().get('/api/v1/admin/groups/4422') av_get_group_document.assert_called_once_with('4422') assert resp_object.status_code == 404 assert resp_object.data == '"no group document found for 4422"'
def setUp(self): super(FrontendTestCase, self).setUp() # Push a request context self.req_ctx = app.test_request_context() self.req_ctx.push() # Create our test client self.client = app.test_client()
def setUp(self): # mock out mail mail_context = mail.record_messages() self.outbox = mail_context.__enter__() self.addCleanup(lambda: mail_context.__exit__(None, None, None)) self.client = app.test_client() super(TestCase, self).setUp()