def test_webapp_publish(self): # tornado does not support windows (yet) self.thisHostMustNot(platform='windows') foo = Foo() wapp = s_webapp.WebApp() wapp.listen(0, host='127.0.0.1') wapp.addApiPath('/v1/horked', foo.horked) wapp.addApiPath('/v1/addup/([0-9]+)', foo.addup) client = AsyncHTTPClient(self.io_loop) port = wapp.getServBinds()[0][1] resp = yield client.fetch('http://127.0.0.1:%d/v1/addup/30?y=40' % port) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp.get('ret'), 70) self.assertEqual(resp.get('status'), 'ok') resp = yield client.fetch('http://127.0.0.1:%d/v1/addup/20' % port) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp.get('ret'), 20) self.assertEqual(resp.get('status'), 'ok') resp = yield client.fetch('http://127.0.0.1:%d/v1/horked' % port) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp.get('err'), 'Horked') self.assertEqual(resp.get('status'), 'err') wapp.fini()
def test_webapp_body(self): # python requests module has windows bug?!?!? self.thisHostMustNot(platform='windows') class Haha: def bar(self, hehe, body=None): return (hehe,body.decode('utf8')) haha = Haha() wapp = s_webapp.WebApp() wapp.listen(0, host='127.0.0.1') wapp.addApiPath('/v1/haha/bar/([a-z]+)', haha.bar) client = AsyncHTTPClient(self.io_loop) port = wapp.getServBinds()[0][1] headers={'Content-Type': 'application/octet-stream'} resp = yield client.fetch('http://127.0.0.1:%d/v1/haha/bar/visi' % port, headers=headers, body='GRONK', allow_nonstandard_methods=True) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual( tuple(resp.get('ret')), ('visi','GRONK') ) resp = yield client.fetch('http://127.0.0.1:%d/v1/haha/bar/visi' % port, method='POST', headers=headers, body='GRONK') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual( tuple(resp.get('ret')), ('visi','GRONK') ) wapp.fini()
def test_webapp_body(self): class Haha: def bar(self, hehe, body=None): return (hehe,body.decode('utf8')) haha = Haha() wapp = s_webapp.WebApp() wapp.listen(0, host='127.0.0.1') wapp.addApiPath('/v1/haha/bar/([a-z]+)', haha.bar) client = AsyncHTTPClient(self.io_loop) port = wapp.getServBinds()[0][1] headers={'Content-Type': 'application/octet-stream'} resp = yield client.fetch('http://127.0.0.1:%d/v1/haha/bar/visi' % port, headers=headers, body='GRONK', allow_nonstandard_methods=True) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual( tuple(resp.get('ret')), ('visi','GRONK') ) resp = yield client.fetch('http://127.0.0.1:%d/v1/haha/bar/visi' % port, method='POST', headers=headers, body='GRONK') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual( tuple(resp.get('ret')), ('visi','GRONK') ) wapp.fini()
def test_webapp_publish(self): # tornado does not support windows (yet) self.thisHostMustNot(platform='windows') foo = Foo() wapp = s_webapp.WebApp() wapp.listen(0, host='127.0.0.1') wapp.addApiPath('/v1/horked', foo.horked ) wapp.addApiPath('/v1/addup/([0-9]+)', foo.addup ) client = AsyncHTTPClient(self.io_loop) port = wapp.getServBinds()[0][1] resp = yield client.fetch('http://127.0.0.1:%d/v1/addup/30?y=40' % port) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual( resp.get('ret'), 70 ) self.assertEqual( resp.get('status'), 'ok' ) resp = yield client.fetch('http://127.0.0.1:%d/v1/addup/20' % port) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual( resp.get('ret'), 20 ) self.assertEqual( resp.get('status'), 'ok' ) resp = yield client.fetch('http://127.0.0.1:%d/v1/horked' % port) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual( resp.get('err'), 'Horked' ) self.assertEqual( resp.get('status'), 'err' ) wapp.fini()
def test_customer_data(self): """Call the '/customer' endpoint and test that the output and database. Verifies that the output can be parsed as JSON. """ client = AsyncHTTPClient(self.io_loop) # First load the database with sample orders to ensure the customer # exists. response = yield client.fetch( "http://*****:*****@example.com', 'total': 100.80})) self.assertEqual(response.code, 200) # Decode bytes into utf-8 string and parse the JSON data = json.loads(response.body.decode('utf-8')) self.assertEqual(100, data["reward_points"]) self.assertEqual("A", data["reward_tier"]) self.assertEqual("5% off purchase", data["reward_tier_name"]) self.assertEqual("10% off purchase", data["next_reward_tier_name"]) self.assertEqual("B", data["next_reward_tier"]) self.assertEqual(0.0, data["next_reward_tier_progress"]) self.assertEqual("*****@*****.**", data["email_address"]) response = yield client.fetch( "http://*****:*****@example.com', 'total': 50})) self.assertEqual(response.code, 200) # Decode bytes into utf-8 string and parse the JSON data = json.loads(response.body.decode('utf-8')) self.assertEqual(150, data["reward_points"]) self.assertEqual("A", data["reward_tier"]) self.assertEqual("5% off purchase", data["reward_tier_name"]) self.assertEqual("10% off purchase", data["next_reward_tier_name"]) self.assertEqual("B", data["next_reward_tier"]) self.assertEqual(0.5, data["next_reward_tier_progress"]) self.assertEqual("*****@*****.**", data["email_address"]) # Call the customer endpoint to verify response = yield client.fetch( "http://*****:*****@example.com'})) self.assertEqual(response.code, 200) # Decode bytes into utf-8 string and parse the JSON data = json.loads(response.body.decode('utf-8')) print("Data: {}".format(data)) self.assertEqual(150, data["reward_points"]) self.assertEqual("A", data["reward_tier"]) self.assertEqual("5% off purchase", data["reward_tier_name"]) self.assertEqual("10% off purchase", data["next_reward_tier_name"]) self.assertEqual("B", data["next_reward_tier"]) self.assertEqual(0.5, data["next_reward_tier_progress"]) self.assertEqual("*****@*****.**", data["email_address"])
def test_register(self): testDict = { 'name': 'loki', 'phone': 'killll', 'email': 'saerty@34', 'password': '******' } client = AsyncHTTPClient() client.fetch()
def test_customer_accessible(self): """Call the '/customer' endpoint to verify the web server is running""" client = AsyncHTTPClient(self.io_loop) response = yield client.fetch("http://*****:*****@example.com'})) self.assertEqual(response.code, 200)
def test_invalid_model(self): self.thisHostMustNot(platform='windows') client = AsyncHTTPClient(self.io_loop) with self.assertRaises(HTTPError) as context: yield client.fetch(self.host + '/v1/horked') self.assertEqual(context.exception.code, 404)
def test_get_with_bad_query(self): client = AsyncHTTPClient() query = "limit=-5&offset=qwe&order=1&order_by=1" response = yield client.fetch( "http://localhost:9090/post?{}".format(query)) self.assertIn(response.code, (200, 201))
def test_idea_add(self): #Add client = AsyncHTTPClient(self.io_loop) resp = yield client.fetch(IDEA_URL) print resp.body self.assertIn("", resp.body)
def do_login(): client = AsyncHTTPClient(self.io_loop) #examlpe url: /mr.login?message=<message in JSON>&other_data_for_the_query_string=value url = self.get_url('/mr.login?message=' + urllib.parse.quote(json.dumps(message0))) response = yield client.fetch(url, method='GET') self.assertEqual(response.code, 200)
def test_get_weather(self): client = AsyncHTTPClient() # first check to see we get a bad response when no city id passed try: response = yield client.fetch("http://localhost:3000/get_weather") # should never reach here but if it does, # the code should not be 200 (all good response) self.assertNotEqual(200, response.code) # expect a 400 error response except httpclient.HTTPClientError: # we got it so ignore it pass # try again, this time with a city ID response = yield client.fetch( "http://localhost:3000/get_weather?city_id=6173331") self.assertEqual(200, response.code) weather_info = json.loads(response.body) # loop all weather updates in the response object # ensure each object has the keys the app will look for for update in weather_info: self.assertIn("weather", update) # ensure there is at least 1 weather object self.assertTrue(len(update['weather']) > 0) self.assertIn("main", update['weather'][0]) self.assertIn("icon", update['weather'][0]) self.assertIn("description", update['weather'][0]) self.assertIn("main", update) self.assertIn("temp", update['main']) self.assertIn("humidity", update['main']) # test the date string self.assertIn("dt_txt", update) # should look like YYYY-MM-DD HH:MM:SS try: date_object = datetime.datetime.strptime( update['dt_txt'], "%Y-%m-%d %H:%M:%S") except ValueError: self.fail('date string format incorrect. %s ' 'does not match YYYY-MM-DD HH:MM:SS' % update['dt_txt']) self.assertTrue(isinstance(date_object, datetime.datetime))
def test_get_with_query(self): client = AsyncHTTPClient() query = "limit=7&offset=1&order=title&order_by=desc" response = yield client.fetch( "http://localhost:9090/post?{}".format(query)) self.assertIn(response.code, (200, 201)) self.assertIn(len(self.get_body(response.body)), (7, ), msg='response len != set limit in query')
def runTest(self): """Ensure our mocking of AsyncHTTPClient functions """ client = AsyncHTTPClient() with mock.patch.object(client, 'fetch') as fetch_mock: static_body = 'hello' static_response_code = 999 _setup_fetch(fetch_mock, static_response_code, static_body) response = yield client.fetch('http://example.com') self.assertEqual(response.code, static_response_code) self.assertEqual(response.body, static_body)
def test_del(self): post_data = { 'user_info': json_encode(user_info), 'module': 'yum', 'host': host, 'package_name': package, 'state': 'absent' } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_shell(self): post_data = { 'user_info': json_encode(user_info), 'host': host, 'module': 'shell', 'args': 'yum list installed |grep httpd', } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_crud_multi(self): self.thisHostMustNot(platform='windows') client = AsyncHTTPClient(self.io_loop) # Can we create tufos? tufo = {} for i in range(2): i = str(i) data = json.dumps({'bar': i, 'key' + i: 'val' + i}) resp = yield client.fetch(self.host + '/v1/bar', method='POST', body=data, headers={'Content-Type': 'application/json'}) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') self.assertDictMust(resp['ret'][1], {'bar': i, 'bar:bar': i, 'bar:key' + i: 'val' + i, 'tufo:form': 'bar',}) tufo[resp['ret'][0]] = resp['ret'][1] # Do they persist? resp = yield client.fetch(self.host + '/v1/bar') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') self.assertEqual(len(resp['ret']), len(tufo)) for rslt in resp['ret']: self.assertDictMust(tufo[rslt[0]],rslt[1]) # Can we get a subset? resp = yield client.fetch(self.host + '/v1/bar?prop=bar:key1&value=val1') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') self.assertEqual(len(resp['ret']), 1) for rslt in resp['ret']: self.assertDictMust(tufo[rslt[0]],rslt[1]) self.assertEqual(rslt[1]['bar:key1'], 'val1') # Can we delete a subset? resp = yield client.fetch(self.host + '/v1/bar?prop=bar:key1&value=val1', method='DELETE') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') resp = yield client.fetch(self.host + '/v1/bar') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') self.assertEqual(len(resp['ret']), 1) for rslt in resp['ret']: self.assertDictMust(tufo[rslt[0]], rslt[1]) self.assertEqual(rslt[1]['bar:key0'], 'val0') # Can they be deleted? resp = yield client.fetch(self.host + '/v1/bar', method='DELETE') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') resp = yield client.fetch(self.host + '/v1/bar') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') self.assertEqual(resp['ret'], [])
def test_systemd(self): post_data = { 'module': 'systemd', 'name': 'httpd', 'state': 'restarted', 'host': host } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_hostname(self): post_data = { 'user_info': json_encode(user_info), 'host': host, 'host_name': '12ff3', 'module': 'hostname' } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_customer_not_exist(self): """Call the '/customer' endpoint and test that the output and database. Verifies that the output can be parsed as JSON. """ client = AsyncHTTPClient(self.io_loop) response = yield client.fetch("http://*****:*****@example.com'})) self.assertEqual(response.code, 200) data = json.loads(response.body.decode('utf-8')) self.assertEqual("CustomerNotFoundError", data[0]["error"]) self.assertIn( "The customer with email '*****@*****.**' was not found in the database.", data[0]["detail"])
def test_add(self): post_data = { 'module': 'copy', 'file_name': 'test', 'host': host, 'content': 'test', 'dest': '/root/1', } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_del_user(self): post_data = { 'user_info': json_encode(user_info), 'host': host, 'module': 'user', 'state': 'present', 'name': 'test2', } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_order_error(self): """Call the '/order' endpoint and test that the output and database. Verifies that the output can be parsed as JSON. """ client = AsyncHTTPClient(self.io_loop) response = yield client.fetch("http://localhost:7050/order", method='POST', body=urlencode({})) self.assertEqual(response.code, 200) data = json.loads(response.body.decode('utf-8')) self.assertEqual("MissingArgumentError", data[0]["error"]) self.assertEqual("MissingArgumentError", data[1]["error"]) self.assertIn("' was not included in the message.", data[0]["detail"]) self.assertIn("' was not included in the message.", data[1]["detail"])
def test_fetch(self): dir = os.path.dirname(os.path.realpath(__file__)) with open('{}/config.yaml'.format(dir), 'r') as stream: config = yaml.load(stream) self.base_url = config['base_url'] connect_db(self.io_loop) Branch.objects.limit(1).find_all(callback=self.stop) branch = self.wait() request = HTTPRequest('{}/api/request_token'.format(self.base_url), headers={ 'ES-Branch': str(branch[0]._id), 'ES-Password': branch[0].password }) client = AsyncHTTPClient(self.io_loop) client.fetch(request, self.handle_request_token) token = self.wait() password = bcrypt.encrypt('1234') users = [] for index in range(0, DATABASE_LIMIT * 2): random = uuid.uuid4() user = User(first_name='APIUsersPaginationTest' + str(random), last_name='last_name' + str(random), email='email' + str(random) + '@localhost.com', password=password, status='Active', credits=300) users.append(user) User.objects.bulk_insert(users, callback=self.stop) self.wait() request = HTTPRequest('{}/api/users'.format(self.base_url), headers={'ES-Token': token}) client = AsyncHTTPClient(self.io_loop) client.fetch(request, self.handle_fetch) self.wait() request = HTTPRequest('{}/api/users?page=1'.format(self.base_url), headers={'ES-Token': token}) client = AsyncHTTPClient(self.io_loop) client.fetch(request, self.handle_fetch) self.wait() User.objects \ .filter({'first_name': {'$regex': '^APIUsersPaginationTest'}}) \ .delete(callback=self.stop) self.wait()
def test_crud_single(self): self.thisHostMustNot(platform='windows') client = AsyncHTTPClient(self.io_loop) # Can we create a tufo? data = json.dumps({'foo': 'val1', 'key2': 'val2'}) tufo = {'foo': 'val1', 'foo:foo': 'val1', 'foo:key2': 'val2', 'tufo:form': 'foo'} resp = yield client.fetch(self.host + '/v1/foo', method='POST', body=data, headers={'Content-Type': 'application/json'}) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') #self.assertEqual(resp['ret'][1], tufo) self.assertDictMust(resp['ret'][1], tufo) iden = resp['ret'][0] # Does it persist? resp = yield client.fetch(self.host + '/v1/foo/' + iden) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') self.assertEqual(resp['ret'], [iden, tufo]) # Can it be updated? data = json.dumps({'key2': 'val22', 'key3': 'val3'}) tufo = {'foo': 'val1', 'foo:foo': 'val1', 'foo:key2': 'val22', 'foo:key3': 'val3', 'tufo:form': 'foo'} resp = yield client.fetch(self.host + '/v1/foo/' + iden, method='PATCH', body=data, headers={'Content-Type': 'application/json'}) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') self.assertEqual(resp['ret'][1], tufo) # Can it be deleted? resp = yield client.fetch(self.host + '/v1/foo/' + iden, method='DELETE') resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') resp = yield client.fetch(self.host + '/v1/foo/' + iden) resp = json.loads(resp.body.decode('utf-8')) self.assertEqual(resp['status'], 'ok') assert resp['ret'] is None
def test_ststderrderrshell_get_user(self): post_data = { # 'user_info': json_encode(user_info), 'host': host, 'module': 'shell', 'args': 'hostname1', } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body) result = json_decode(response.body) print(result)
def test_fetch(self): dir = os.path.dirname(os.path.realpath(__file__)) with open('{}/config.yaml'.format(dir), 'r') as stream: config = yaml.load(stream) self.base_url = config['base_url'] connect_db(self.io_loop) Branch.objects.limit(1).find_all(callback=self.stop) branch = self.wait() Instructor.objects.limit(2).find_all(callback=self.stop) instructors = self.wait() self.schedule = InstructorSchedule() self.schedule.branch = branch[0]._id self.schedule.seats = 37 self.schedule.start = parser.parse('1:0', default=self.DEFAULT_TIME) self.schedule.end = parser.parse('2:0', default=self.DEFAULT_TIME) self.schedule.date = parser.parse(date.today().strftime('%Y-%m-%d')) self.schedule.type = 'any' self.schedule.instructor = instructors[0]._id self.schedule.sub_instructor = instructors[1]._id self.schedule.save(callback=self.stop) self.wait() client = AsyncHTTPClient(self.io_loop) client.fetch( '{}/admin/schedule?date={}'.format( self.base_url, date.today().strftime('%Y-%m-%d')), self.handle_fetch) self.wait() self.schedule.delete(callback=self.stop) self.wait()
def test_rewards_data(self): """Call the '/rewards' endpoint and test that the output. Verifies that the output can be parsed as JSON and the data matches the supplied test data. """ client = AsyncHTTPClient(self.io_loop) response = yield client.fetch("http://localhost:7050/rewards") self.assertEqual(response.code, 200) # Decode bytes into utf-8 string and parse the JSON data = json.loads(response.body.decode('utf-8')) # Sort the JSON output so we know the first tier is tier A, # at least based on the supplied test data. rewards = sorted(data, key=itemgetter("points")) self.assertEqual("A", rewards[0]["tier"]) self.assertEqual(100, rewards[0]["points"]) self.assertEqual("5% off purchase", rewards[0]["rewardName"])
def test_masquerade(self): post_data = { 'user_info': json_encode(user_info), 'host': host, 'permanent': 'true', 'state': 'enabled', 'masquerade': 'yes', 'zone': 'public', 'module': 'firewalld' } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_add_user_groups(self): post_data = { 'user_info': json_encode(user_info), 'host': host, 'module': 'user', 'state': 'present', 'name': 'test3', 'password': password, 'groups': 'test2,root' } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_service(self): post_data = { 'user_info': json_encode(user_info), 'host': host, 'permanent': 'false', 'state': 'enabled', 'service': 'http', 'immediate': 'false', 'module': 'firewalld' } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_update_passwd(self): new_passwd = sha512_crypt.using(rounds=5000).hash('milan') print(new_passwd) post_data = { 'user_info': json_encode(user_info), 'host': host, 'module': 'user', 'name': 'test2', 'state': 'update', 'password': new_passwd, 'update_password': '******' } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_del(self): post_data = { 'user_info': json_encode(user_info), 'module': 'yum_repo', 'host': host, 'name': 'wanda', 'state': 'absent', 'description': 'local', 'enabled': '1', 'gpgcheck': '0', 'baseurl': 'http://yum.wanda.cn' } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def test_add(self): post_data = { "server_id": 17, "server_name": "slave23", "manager_ip": "172.16.250.23", "ilo4_user_name": "admin", "ilo4_user_passwd": "cGFzc3dvcmQ=", "server_ip": "172.16.251.106", "server_group": "test", "server_idc": "成都", "pt_id": 2 } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='PUT', body=json_encode(post_data)) print(response.body)
class TestHandlerBase(AsyncTestCase): def setUp(self): super(TestHandlerBase, self).setUp() self.client = AsyncHTTPClient(self.io_loop) def tearDown(self): pass def testgetItems(self): res = self.client.fetch('ok') self.wait() assert res.code == 412 def get_app(self): import alfred.webserver return alfred.webserver.WebServer().start()
def test_login(self): client = AsyncHTTPClient(self.io_loop) message0 = {"type": "login", "payload": "django"} url = self.get_url('/mr.login?message=' + urllib.parse.quote(json.dumps(message0))) response = yield client.fetch(url, method='GET') self.assertEqual(response.code, 200) bodystr = None try: bodystr = response.body.decode("utf-8") except ValueError: self.fail("Mr. Login gave an invalid response to a login; it was not valid utf-8; response: %s" % repr(response.body)) login_response = None try: login_response = json.loads(bodystr) except ValueError: self.fail("Mr. Login gave an invalid response to a login; it was not valid json; response: %s" % repr(response.body)) self.assertTrue( isinstance(login_response, dict), msg=login_response ) self.assertTrue( 'success' in login_response, msg=login_response ) self.assertTrue( isinstance(login_response['success'], bool), msg=login_response ) self.assertTrue( login_response['success'], msg=login_response ) self.assertTrue( 'msg' in login_response, msg=login_response ) self.assertTrue( isinstance(login_response['msg'], str), msg=login_response ) cache = self.myapp.global_message_buffer.cache self.assertTrue( len(cache) > 0, msg=cache ) self.assertTrue( cache[-1]['type'] == message0['type'] ) self.assertTrue( cache[-1]['payload'] == message0['payload'] )
def test_login(self): client = AsyncHTTPClient(self.io_loop) message0 = {"type": "login", "payload": "django"} url = self.get_url('/mr.login?message=' + urllib.parse.quote(json.dumps(message0))) response = yield client.fetch(url, method='GET') self.assertEqual(response.code, 200) bodystr = None try: bodystr = response.body.decode("utf-8") except ValueError: self.fail( "Mr. Login gave an invalid response to a login; it was not valid utf-8; response: %s" % repr(response.body)) login_response = None try: login_response = json.loads(bodystr) except ValueError: self.fail( "Mr. Login gave an invalid response to a login; it was not valid json; response: %s" % repr(response.body)) self.assertTrue(isinstance(login_response, dict), msg=login_response) self.assertTrue('success' in login_response, msg=login_response) self.assertTrue(isinstance(login_response['success'], bool), msg=login_response) self.assertTrue(login_response['success'], msg=login_response) self.assertTrue('msg' in login_response, msg=login_response) self.assertTrue(isinstance(login_response['msg'], str), msg=login_response) cache = self.myapp.global_message_buffer.cache self.assertTrue(len(cache) > 0, msg=cache) self.assertTrue(cache[-1]['type'] == message0['type']) self.assertTrue(cache[-1]['payload'] == message0['payload'])
def test_http_fetch(self): print("testMainHandler") client = AsyncHTTPClient(self.io_loop) response = yield client.fetch("http://localhost:8080") # Test contents of response self.assertEqual("hello world", response.body)
def test_broadcast(self): message0 = {"type": "login", "payload": "django"} @tornado.gen.coroutine def do_login(): client = AsyncHTTPClient(self.io_loop) #examlpe url: /mr.login?message=<message in JSON>&other_data_for_the_query_string=value url = self.get_url('/mr.login?message=' + urllib.parse.quote(json.dumps(message0))) response = yield client.fetch(url, method='GET') self.assertEqual(response.code, 200) yield do_login() client = AsyncHTTPClient(self.io_loop) url = self.get_url('/mr.broadcaster?cursor=100002325435') response = yield client.fetch(url, method='GET') self.assertEqual(response.code, 200) bodystr = None try: bodystr = response.body.decode("utf-8") except ValueError: self.fail("Mr. Broadcaster gave an invalid response to a broadcast request; it was not valid utf-8; response: %s" % repr(response.body)) broadcast = None try: broadcast = json.loads(bodystr) except ValueError: self.fail("Mr. Broadcaster gave an invalid response to a broadcast request; it was not valid json; response: %s" % repr(response.body)) self.assertTrue( isinstance(broadcast, dict), msg=broadcast ) self.assertTrue( 'messages' in broadcast, msg=broadcast ) self.assertTrue( isinstance(broadcast['messages'], list), msg=broadcast ) found_login_message = False for message in broadcast['messages']: self.assertTrue( isinstance(message, dict), msg=message ) self.assertTrue( 'id' in message, msg=message ) self.assertTrue( isinstance(message['id'], (int,str)), msg=message ) self.assertTrue( 'type' in message, msg=message ) self.assertTrue( isinstance(message['type'], str), msg=message ) self.assertTrue( message['type'] in ['login'], msg=message ) self.assertTrue( 'payload' in message, msg=message ) if (message['type'] == 'login'): self.assertTrue( isinstance(message['payload'], str), msg=message ) if message['type'] == 'login' and message['payload'] == 'django': found_login_message = True self.assertTrue(found_login_message , msg='Did not find the expected login message that we gave Mr. login; message0: %s, broadcast: %s' % (message0, broadcast))
def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.tornadoweb.org/", self.handle_fetch) self.wait()
def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.tornadoweb.org/", self.stop) response = self.wait() # Test contents of response self.assertIn("FriendFeed", response.body)
def test_index_fetch(self): client = AsyncHTTPClient(self.io_loop) resp = yield client.fetch(INDEX_URL) self.assertIn("hello", resp.body)
def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.baidu.com/", self.handle_fetch) self.wait()
def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.baidu.com/", self.stop) response = self.wait() print(response)
def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) response = yield client.fetch("http://www.baidu.com") # Test contents of response print(response)