class TestLogin(APITestCase): def setUp(self): if not User.objects.filter(username='******').exists(): self.admin = User.objects.create_superuser(username="******", password="******", email="*****@*****.**") self.admin_token, _ = Token.objects.get_or_create(user=self.admin) self.client = RequestsClient() self.maxDiff = None def test_empty(self): response = self.client.post('http://127.0.0.1:8000/users/login/') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_wrong_authentication(self): response = self.client.post('http://127.0.0.1:8000/users/login/', json={ "username": "******", "password": "******" }) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_valid(self): response = self.client.post('http://127.0.0.1:8000/users/login/', json={ "username": "******", "password": "******" }) self.assertEqual(response.status_code, status.HTTP_200_OK)
class TestRegister(APITestCase): def setUp(self): if not User.objects.filter(username='******').exists(): self.admin = User.objects.create_superuser(username="******", password="******", email="*****@*****.**") self.admin_token, _ = Token.objects.get_or_create(user=self.admin) if not User.objects.filter(username='******').exists(): self.normal_user = User.objects.create_user( username="******", password="******", email="*****@*****.**") self.normal_user_token, _ = Token.objects.get_or_create( user=self.normal_user) self.client = RequestsClient() self.maxDiff = None def test_no_permission(self): self.client.headers.update( {"Authorization": self.normal_user_token.key}) response = self.client.post('http://127.0.0.1:8000/users/', json={ "username": "******", "password": "******", "email": "*****@*****.**" }) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_valid(self): self.client.headers.update({"Authorization": self.admin_token.key}) response = self.client.post('http://127.0.0.1:8000/users/', json={ "username": "******", "password": "******", "email": "*****@*****.**" }) self.assertEqual(response.status_code, status.HTTP_200_OK)
class TestCanLogin(TestCase): def setUp(self) -> None: ClientUser.objects.create(consumer_key='pass', consumer_secret='pass') self.client = RequestsClient() self.client.auth = HTTPBasicAuth('pass', 'pass') self.client.headers.update({'x-test': 'true'}) url = reverse('get_token') response = self.client.post('http://testserver{}'.format(url)) self.token = response.json().get('access_token') self.client = RequestsClient() self.client.headers.update( {'Authorization': 'Bearer {}'.format(self.token)}) url = reverse('register') self.client.post('http://testserver{}'.format(url), json={ 'msisdn': 254763488092, 'pin': 1212 }) def test_can_login(self): client = RequestsClient() url = reverse('login') client.headers.update( {'Authorization': 'Bearer {}'.format(self.token)}) response = client.post('http://testserver{}'.format(url), json={ 'msisdn': 254763488092, 'pin': 1212 }) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_login(self): client = RequestsClient() response = client.get("http://testserver/accounts/login") csrftoken = response.cookies['csrftoken'] user = models.CaseUser.objects.get(email="*****@*****.**") user_password = "******" """ Testing valid login """ response = client.post("http://testserver/accounts/view_details/", json={'email': user.email, 'password': user_password}, headers={'X-CSRFToken': csrftoken}) assert response.status_code == 200 soup = BeautifulSoup(response.content, 'html.parser') api_key = soup.findAll("span", {"class": "user_api_key"})[0].text assert api_key == models.Token.objects.get(user=user).key case_allowance = soup.findAll("span", {"class": "user_case_allowance"})[0].text assert case_allowance == "500" """ Testing invalid login """ response = client.post("http://testserver/accounts/view_details/", json={'email': user.email, 'password': user_password + "1"}, headers={'X-CSRFToken': csrftoken}) assert response.status_code == 400
def test_weather_temperature_filter_request(self): client = RequestsClient() client.get(BASE_URL + 'weather/') client.post(BASE_URL + 'weather/', json=self.weather2) client.post(BASE_URL + 'weather/', json=self.weather1) client.post(BASE_URL + 'weather/', json=self.weather3) res = client.get(BASE_URL + 'weather/temperature?start=1985-02-01&end=1985-02-02') self.assertEqual(res.status_code, 200) self.assertEqual(res.json(), []) self.assertEqual(len(res.json()), 0) res = client.get(BASE_URL + 'weather/temperature?start=1985-01-01&end=1985-01-02') self.assertEqual(res.status_code, 200) self.assertEqual(len(res.json()), 2) self.assertEqual(res.json()[0]['lowest'], 2.7) self.assertEqual(res.json()[0]['highest'], 91.3) self.assertEqual(res.json()[1]['lowest'], 39.8) self.assertEqual(res.json()[1]['highest'], 53.5) res = client.get(BASE_URL + 'weather/temperature?start=1985-01-01&end=1985-01-04') self.assertEqual(res.status_code, 200) self.assertEqual(len(res.json()), 3) self.assertEqual(res.json()[0]['city'], 'Monroe') self.assertEqual(res.json()[0]['state'], 'Louisiana') self.assertEqual(res.json()[1]['city'], 'Monroe') self.assertEqual(res.json()[1]['state'], 'Tennessee') self.assertEqual(res.json()[2]['city'], 'Nashville') self.assertEqual(res.json()[2]['state'], 'Tennessee')
class AuthenticationTests(APITestCase, TestCase): def setUp(self): self.client = RequestsClient() self.user = User.objects.create_user(username="******", password="******") token, created = Token.objects.get_or_create(user=self.user) self.key = token.key self.url = URL Event.objects.create( collection_id="0", collection_title="blank", action="added", datetime="2000-11-01", ) def test_anonymous_get(self): """ Test anonymous user can GET request successfully """ response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), [ { "collection_id": "0", "collection_title": "blank", "action": "added", "datetime": "2000-11-01", } ], ) def test_unauthenticated_post(self): """ Test unauthenticated users are 401 Forbidden to POST request """ headers = { "Content-Type": "application/json", "Accept": "application/json", } data = json.dumps(MULTI_ITEM_JSON, indent=4) response = self.client.post(self.url, data=data, headers=headers) self.assertEqual(response.status_code, 401) def test_authenticated_post(self): """ Test authenticated users are allowed to POST request with 201 Create """ headers = { "Authorization": f"Token {self.key}", "Content-Type": "application/json", "Accept": "application/json", } data = json.dumps(MULTI_ITEM_JSON, indent=4) response = self.client.post(self.url, data=data, headers=headers) self.assertEqual(response.status_code, 201)
class TestSingleImageAPIFromExternalPerspective(APILiveServerTestCase): def setUp(self) -> None: self.user = get_custom_user(username='******', password='******') Token.objects.create(user=self.user) self.client = RequestsClient() api_group = Group.objects.create(name="API") self.user.groups.add(api_group) # Create wagtail collection used during image upload view root_coll = WagtailCollection.get_first_root_node() root_coll.add_child(name='BRAHMS Data') self.family = get_family() self.genus = get_genus(self.family) self.species = get_species(self.genus) token_url = self.live_server_url + reverse('plants:api-token') response = self.client.post(token_url, data={ 'username': '******', 'password': '******' }) token = {'drf_token': response.json()['token']} self.client.headers.update({ 'Accept': 'application/json; q=1.0, */*', 'Authorization': 'Token ' + token['drf_token'] }) self.img_file_obj = BytesIO() image_one = Image.new('RGB', size=(1, 1), color=(256, 0, 0)) image_one.save(self.img_file_obj, 'jpeg') self.img_file_obj.seek(0) self.img_one = ImageFile(self.img_file_obj, name='1.jpg') def tearDown(self) -> None: self.img_file_obj.close() def test_posting_species_image(self): url = self.live_server_url + reverse('plants:api-set-species-image', kwargs={'pk': self.species.pk}) test_copyright_info = 'Example Copyright Info' self.assertRaises(SpeciesImage.DoesNotExist, SpeciesImage.objects.get, species=self.species) r = self.client.post(url, data={'copyright_info': test_copyright_info}, files={'image': self.img_one}) self.assertTrue(status.is_success(r.status_code)) species_image = SpeciesImage.objects.get(species=self.species) self.assertEqual(species_image.copyright, test_copyright_info)
class TestApiSensor(TestCase): """Class to test CRUD in Sensor API.""" def setUp(self): """ Setup a sensor, user and login to perform the requests. """ self.config = Config() self.data = Data() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.sensor = Sensor.objects.create(name='name', description='description', external_id='external_id') self.client = RequestsClient() response = self.client.post(self.config.AUTH_URL, data={ 'username': '******', 'password': '******' }) self.assertIn('token', response.json()) self.token = response.json()['token'] self.headers = {'Authorization': f"Token {self.token}"} def test_api_sensor_get_all(self): """ Retrieve all the sensors. """ response = self.client.get(self.config.API_URL + '/sensors/', headers=self.headers) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_api_sensor_get_id(self): """ Retrieve a single sensor that we initialized and test the data is correct. """ response = self.client.get(self.config.API_URL + f'/sensors/{self.sensor.external_id}/', headers=self.headers) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()['name'], 'name') self.assertEqual(response.json()['description'], 'description') self.assertEqual(response.json()['external_id'], 'external_id') def test_api_sensor_create(self): """ Create a sensor and test the data is valid. """ response = self.client.post(self.config.API_URL + '/sensors/', headers=self.headers, data=self.data.sensor_request) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.json()['name'], self.data.sensor_request['name']) self.assertEqual(response.json()['description'], self.data.sensor_request['description']) self.assertEqual(response.json()['external_id'], self.data.sensor_request['external_id'])
class SerializerTests(APITestCase, TestCase): def setUp(self): self.client = RequestsClient() self.user = User.objects.create_user(username="******", password="******") token, created = Token.objects.get_or_create(user=self.user) self.key = token.key self.url = URL self.headers = { "Authorization": f"Token {self.key}", "Content-Type": "application/json", "Accept": "application/json", } def test_json_to_model(self): """ Test JSON object is successfully and accurately converted to Events Model Object """ data = [ { "collection_id": "0", "collection_title": "blank", "action": "added", "datetime": datetime.datetime.today().strftime('%Y-%m-%d'), } ] data = json.dumps(data, indent=4) response = self.client.post(self.url, data=data, headers=self.headers) model = Event.objects.all().first() post_json = response.json()[0] self.assertTrue(Event.objects.all()) self.assertEqual(model.collection_title, post_json.get("collection_title")) self.assertEqual(model.collection_id, post_json.get("collection_id")) self.assertEqual(model.datetime.strftime("%Y-%m-%d"), post_json.get("datetime")) def test_invalid_format_request(self): """ Test invalid JSON of wrong format returns 400 Bad Request """ data = [{"invalid": "format"}] data = json.dumps(data, indent=4) response = self.client.post(self.url, data=data, headers=self.headers) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), [ { "collection_id": ["This field is required."], "collection_title": ["This field is required."], "action": ["This field is required."], "datetime": ["This field is required."], } ], )
def testSet3(self): client = RequestsClient() res = client.post(self.host + self.post_sample_api,json={'source':'TestCase'}) for ro in self.test_3: row = json.loads(ro) res = {} if row['request']['method'] == "GET": url = self.host + row['request']['url'] + '/' res = client.get(url) elif row['request']['method'] == "POST": res = client.post( self.host + row['request']['url'] + '/', json=row['request']['body']) self.assertEqual(res.status_code, row['response']['status_code']) self.assertEqual(json.loads(res.text), row['response']['body'])
def test_weather_filter_request(self): client = RequestsClient() client.get(BASE_URL + 'weather/') client.post(BASE_URL + 'weather/', json=self.weather2) client.post(BASE_URL + 'weather/', json=self.weather1) client.post(BASE_URL + 'weather/', json=self.weather3) res = client.get(BASE_URL + 'weather?lat=36.1189&lon=-86.6892') self.assertEqual(res.status_code, 200) self.assertEqual(res.json(), [self.weather1, self.weather2]) res = client.get(BASE_URL + 'weather?lat=35.1189&lon=-16.6892') self.assertEqual(res.status_code, 200) self.assertEqual(res.json(), [self.weather3]) res = client.get(BASE_URL + 'weather?lat=12.3232&lon=-34.1234') self.assertEqual(res.status_code, 404, 'There is no weather data with given lat and lon')
def test_question_post(self): print("Test question post") client = RequestsClient() url = 'http://127.0.0.1:8000/api/question/' data = {"name": "John", "question": "Where is my socks?"} response = client.post(url=url, data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED)
class WeatherEndpointWithDELETESingleTestCase(TestCase): def setUp(self): self.client = RequestsClient() self.url = HOST + '/weather/' try: self.chicago = self.client.post(self.url, data=chicago).json() except JSONDecodeError: self.fail( "/weather/ endpoint for POST request not implemented correctly" ) def test_with_existing_record(self): chicago_url = '%s%s' % (self.url, self.chicago['id']) r = self.client.delete(chicago_url) self.assertEqual(r.status_code, status.HTTP_204_NO_CONTENT) r = self.client.get(chicago_url) self.assertEqual(r.status_code, status.HTTP_404_NOT_FOUND) def test_with_non_existing_record(self): non_existing_id = 2 self.assertNotEqual(non_existing_id, self.chicago['id']) non_existing_url = '%s%s' % (self.url, non_existing_id) r = self.client.delete(non_existing_url) self.assertEqual(r.status_code, status.HTTP_404_NOT_FOUND)
def test_auth(self): # Confirm session is not authenticated client = RequestsClient() response = client.get('http://testserver/auth/') assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = {'username': None} assert response.json() == expected assert 'csrftoken' in response.cookies csrftoken = response.cookies['csrftoken'] user = User.objects.create(username='******') user.set_password('password') user.save() # Perform a login response = client.post('http://testserver/auth/', json={ 'username': '******', 'password': '******' }, headers={'X-CSRFToken': csrftoken}) assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = {'username': '******'} assert response.json() == expected # Confirm session is authenticated response = client.get('http://testserver/auth/') assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = {'username': '******'} assert response.json() == expected
class ApiTestCase(AdminLoggedOutTestCase): ''' We take the more complicated way here, and implement the API tests with Python requests. This ensures that we are getting as close as possible to 'real' API clients, e.g. from JavaScript. ''' def setUp(self): super().setUp() self.client = RequestsClient() # Obtain the CSRF token for later POST requests response = self.get('/') self.assertEquals(response.status_code, 200) self.csrftoken = response.cookies['csrftoken'] def get(self, relative_url): return self.client.get('http://testserver' + relative_url) def post(self, relative_url, data={}): return self.client.post('http://testserver' + relative_url, json=data, headers={'X-CSRFToken': self.csrftoken}) def api_login(self): response = self.post(F'/api/{API_VERSION}/login', {'username': admin_data['username'], 'password': admin_clear_password}) self.assertEquals(response.status_code, 200) # The login API call returns the JWT + extra information as JSON in the body, but also sets a cookie with the JWT. # This means that for all test cases here, the JWT must not handed over explicitely, # since the Python http client has the cookie anyway. self.jwt = response.json()["access_token"] assert('kubeportal-auth' in response.cookies) self.assertEquals(response.cookies['kubeportal-auth'], self.jwt)
def test_post2(self): """ Ensure an User can NOT POST a custom Task on a trip he doesn't own. """ test_user2 = User.objects.create_user("loic", "secret") token = Token.objects.get(user__username='******') client = RequestsClient() client.headers.update({"Authorization": f'Token {token.key}'}) trip_id = self.test_trip.id old_tasks_count = self.test_trip.tasks.count() response = client.post('http://127.0.0.1:8000/tasks/', json={ "trip": trip_id, "title": "Test", "deadline": None, "completed": True, "comments": "ceci est un test", "auto": True, "isVisible": True }, headers={"Content-Type": 'application/json'}) self.assertEqual(response.status_code, 403) self.assertEqual(self.test_trip.tasks.count(), old_tasks_count)
def test_API_user(self): # client = RequestsClient() # # # Obtain a CSRF token. # response = client.get('http://127.0.0.1:9090/api-auth/login/') # assert response.status_code == 200 # csrftoken = response.cookies['csrftoken'] # # # Interact with the API. # response = client.post('http://127.0.0.1:9090/api-auth/login/', json={ # 'username': '******', # 'password': '******' # }, headers={'X-CSRFToken': csrftoken}) # assert response.status_code == 200 from requests.auth import HTTPBasicAuth # Include an appropriate `Authorization:` header on all requests. # token = Token.objects.get(user__username='******') # client = APIClient() # client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) client = RequestsClient() client.auth = HTTPBasicAuth('jody', 'rekless') # client.headers.update({'x-test': 'true'}) test = client.login() response = client.post('http://127.0.0.1:9090/api-auth/login/') assert response.status_code == 200
def test_authorized_access(self): """ Test an authorized access to all endpoints Note : creates a user request the login endpoint of the app gets the token request the endpoints and checks the response's code """ client = RequestsClient() self.user = User.objects.create_user(username='******', password='******') params = {'username': '******', 'password': '******'} response = client.post('http://127.0.0.1:8000/api/token/', params) json_array = response.json() header = { "Authorization": "Bearer " + json_array['access'] } response = client.get('http://127.0.0.1:8000/api/v1.0/input/waypoint/', headers = header) assert response.status_code == 200 response = client.get('http://127.0.0.1:8000/api/v1.0/input/path', headers=header) assert response.status_code == 200 response = client.get('http://127.0.0.1:8000/api/v1.0/input/acceleration', headers=header) assert response.status_code == 200
class SigninApiTest(APITestCase): def setUp(self): self.obj = Profile.objects.create_user( username='******', password='******', name='Leonardo', full_display_name='Leonardo Gregório', email='*****@*****.**') self.client = RequestsClient() def test_get(self): """Get /signin/ must return status 405""" response = self.client.get('http://127.0.0.1:8000/signin/') self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_authenticate_user(self): """Ensure we can authenticate a user.""" data_to_authenticate = { "username": "******", "password": "******" } response = self.client.post( 'http://127.0.0.1:8000/signin/', data=data_to_authenticate) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_task_one_api_test_three(self): client = RequestsClient() content = {"queries": ["my life change", "i love coding"], "k": 3} response = client.post('http://127.0.0.1:8000/book/getInfoList/', json=content) data = json.loads(response.text) self.assertEqual(len(data), 2)
class MusicRecommenderApiTest(APITestCase): fixtures = ['artists_fixture.json'] def setUp(self): self.client = RequestsClient() self.pre_http = "http://127.0.0.1:8000" def test_get_recommendation(self): data = {'artist': 'die Ärzte', 'number': 5} url = self.pre_http + reverse('artist_recommendation_api') response = self.client.post(url, data=data) recommendations = json.loads(response.content.decode("utf-8"))['recommendations'] self.assertEqual(5, len(recommendations)) self.assertEqual(response.status_code, 200) """ def test_get_recommendation(self): url = self.pre_http + reverse('artist_recommendation_api', kwargs={'artist': "die Ärzte", 'number': 5}) response = self.client.get(url) recommendations = json.loads(response.content.decode("utf-8"))['recommendations'] self.assertEqual(5, len(recommendations)) self.assertEqual(response.status_code, 200) """ def test_get_artists(self): url = self.pre_http + reverse('artist_list_api') response = self.client.get(url) artists = json.loads(response.content.decode('utf-8')) self.assertTrue(len(artists) > 0) self.assertTrue("id" in artists[0]) self.assertTrue("name" in artists[0])
def test_post0(self): """ Ensure a User can POST a Trip. """ token = Token.objects.get(user__username='******') client = RequestsClient() client.headers.update({"Authorization": f'Token {token.key}'}) old_trips_count = self.test_user.trips.count() response = client.post( "http://127.0.0.1:8000/trips/", json={ "departure_airport": "CTU", "departure_country": "China", "departure_date_time": "2017-12-06T18:00:00Z", "arrival_airport": "IAT", "arrival_country": "France", "arrival_date_time": "2017-12-07T09:30:00Z", "segments": [] }, headers={"Content-Type": 'application/json'}) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( self.test_user.trips.count(), old_trips_count+1)
def invoke_post(self, first_level_directory: str): client = RequestsClient() return client.post( f"http://localhost/{first_level_directory}", json={ "type": "message", "id": "bf3cc9a2f5de...", "timestamp": "2016-10-19T20:17:52.2891902Z", "serviceUrl": "https://smba.trafficmanager.net/apis", "channelId": "SLACK", "from": { "id": "FROMID", "name": "user's name" }, "conversation": { "id": "CONVERSATIONID", "name": "conversation's name" }, "recipient": { "id": "RECIPIENTID", "name": "bot's name" }, "text": "Haircut on Saturday", }, )
def list_todo(self, api_key, action, sort_by, filter_title_by, filter_description_by, filter_state_by, filter_due_date_by, reverse_order): if api_key == "": msg = _('API Key must not be empty.') raise ValidationError({'error': msg}) else: if action == 'get': response = client.get( 'http://localhost:8000/todoapp/api/list/', headers={'Authorization': 'Api-Key %s' % api_key}) return response else: client = RequestsClient() try: sort_choices = [ 'task_title', 'task_description', 'task_state', 'task_due_date' ] data = { "sort_by": sort_by, "filter_title_by": filter_title_by, "filter_description_by": filter_description_by, "filter_state_by": filter_state_by, "filter_due_date_by": filter_due_date_by, "reverse_order": reverse_order, } response = client.post( 'http://localhost:8000/todoapp/api/list/', data, headers={'Authorization': 'Api-Key %s' % api_key}) return response except Exception as e: raise ValidationError({'error': e.args})
def test_post0(self): """ Ensure a User can POST a custom Task on one of its trips. """ token = Token.objects.get(user__username='******') client = RequestsClient() client.headers.update({"Authorization": f'Token {token.key}'}) trip_id = self.test_trip.id old_tasks_count = self.test_trip.tasks.count() response = client.post('http://127.0.0.1:8000/tasks/', json={ "trip": trip_id, "title": "Test", "category": "Health", "deadline": None, "completed": True, "comments": "ceci est un test", "auto": True, "isVisible": True }, headers={"Content-Type": 'application/json'}) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(self.test_trip.tasks.count(), old_tasks_count + 1)
class SpeakerAPIConsumerTest(APILiveServerTestCase): def setUp(self): self.client = RequestsClient() self.event = Event.objects.create(name='TEDx 2019') for _ in range(MAX_OBJECTS): self.speaker = Speaker.objects.create(event=self.event) def test_api_can_create_sponsor(self): speakers_url = self.live_server_url + '/speakers/' data = { "first_name": "Masoud", "last_name": "Algoone", "email": "*****@*****.**", "phone_number": "09375178053", "bio": "Guide Them All", } response = self.client.post(speakers_url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_api_can_retrieve_speakers(self): speakers_url = self.live_server_url + '/speakers/' client = self.client response = client.get(speakers_url) json_data = response.json() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_data), MAX_OBJECTS)
def test_get_all_trades_small(self): client = RequestsClient() for ro in self.test_small: row = json.loads(ro) res = {} if row['request']['method'] == "GET": res = client.get('http://localhost:8000' + row['request']['url'] + '/') elif row['request']['method'] == "POST": res = client.post('http://localhost:8000' + row['request']['url'] + '/', json=row['request']['body']) elif row['request']['method'] == "DELETE": res = client.delete('http://localhost:8000' + row['request']['url'] + '/') self.assertEqual(res.status_code, row['response']['status_code']) if row['response']['headers'] != {}: self.assertEqual(res.headers['Content-Type'], row['response']['headers']['Content-Type']) if row['response']['body'] != {}: response = json.loads(res.text) for resp in response: if resp['trade_timestamp']: temp = parse(resp['trade_timestamp']) temp = temp.replace(tzinfo=None) temp = str(temp) resp['trade_timestamp'] = temp self.assertEqual(response, row['response']['body'])
def test_category_post(self): print("Post category") url = 'http://testserver/categories/' client = RequestsClient() data = {'name': 'Languages', 'imgpath': 'someimg'} response = client.post(url, data) self.assertEquals(response.status_code, status.HTTP_200_OK)
def test_set_3(self): client = RequestsClient() for ro in self.test_3: row = json.loads(ro) res = {} if row['request']['method'] == "GET": res = client.get('http://localhost:8000' + row['request']['url'] + '/') elif row['request']['method'] == "POST": res = client.post( 'http://localhost:8000' + row['request']['url'] + '/', json=row['request']['body']) elif row['request']['method'] == "DELETE": res = client.delete( 'http://localhost:8000' + row['request']['url'] + '/') elif row['request']['method'] == "PUT": res = client.put('http://localhost:8000' + row['request']['url'] + '/', json=row['request']['body']) self.assertEqual(res.status_code, row['response']['status_code']) if row['response']['headers'] != {}: self.assertEqual( res.headers['Content-Type'], row['response']['headers']['Content-Type']) if row['request']['url'] in ['/actors','/actors/streak'] and row['request']['method'] == 'GET': self.assertEqual(sorted(json.loads(res.text)), sorted(row['response']['body'])) elif row['response']['body'] != {}: response = json.loads(res.text) for resp in response: if resp['created_at']: temp = parse(resp['created_at']) temp = temp.replace(tzinfo=None) temp = str(temp) resp['created_at'] = temp self.assertEqual(response, row['response']['body'])
class TestAPIViews(TestCase): def test_root(self): client = RequestsClient() response = client.get('http://127.0.0.1:8000/api/') self.assertEqual(response.status_code, 200) def gen_token(self): user = User.objects.create_user('teste', '*****@*****.**', 'teste') data = {'username': '******', 'password': '******'} response = self.client.post('http://127.0.0.1:8000/api/api-token-auth/', data=data) self.token = response.json()['token'] def _login(self): self.client = RequestsClient() self.gen_token() self.headers = {'Authorization': f'Token {self.token}'} def test_token(self): self._login() self.assertIsNotNone(self.token) def create_todo(self): data = {'todo': 'teste'} response = self.client.post('http://127.0.0.1:8000/api/todos/', headers=self.headers, data=data) return response def test_create_todo(self): self._login() response = self.create_todo() self.assertEqual(response.status_code, 201) def test_get_todo(self): self._login() new_todo = self.create_todo() pk = new_todo.json()['id'] response = self.client.get(f'http://127.0.0.1:8000/api/todos/{pk}/', headers=self.headers) self.assertEqual(response.status_code, 200) def test_delete_todo(self): self._login() new_todo = self.create_todo() pk = new_todo.json()['id'] response = self.client.delete(f'http://127.0.0.1:8000/api/todos/{pk}/', headers=self.headers) self.assertEqual(response.status_code, 204) def test_put_todo(self): self._login() new_todo = self.create_todo() pk = new_todo.json()['id'] data = {'todo': 'Teste!'} response = self.client.put(f'http://127.0.0.1:8000/api/todos/{pk}/', headers=self.headers, data=data) self.assertEqual(response.status_code, 200) def test_list_todos(self): self._login() new_todo = self.create_todo() response = self.client.get('http://127.0.0.1:8000/api/todos/', headers=self.headers) self.assertEqual(response.status_code, 200)
def test_post_json_request(self): client = RequestsClient() response = client.post('http://testserver/', json={'key': 'value'}) assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = { 'method': 'POST', 'query_params': {}, 'POST': {}, 'FILES': {}, 'JSON': {'key': 'value'} } assert response.json() == expected
def test_post_multipart_request(self): client = RequestsClient() files = { 'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n') } response = client.post('http://testserver/', files=files) assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = { 'method': 'POST', 'query_params': {}, 'FILES': {'file': ['report.csv', 'some,data,to,send\nanother,row,to,send\n']}, 'POST': {}, 'JSON': None } assert response.json() == expected
def test_session(self): client = RequestsClient() response = client.get('http://testserver/session/') assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = {} assert response.json() == expected response = client.post('http://testserver/session/', json={'example': 'abc'}) assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = {'example': 'abc'} assert response.json() == expected response = client.get('http://testserver/session/') assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = {'example': 'abc'} assert response.json() == expected
def test_auth(self): # Confirm session is not authenticated client = RequestsClient() response = client.get('http://testserver/auth/') assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = { 'username': None } assert response.json() == expected assert 'csrftoken' in response.cookies csrftoken = response.cookies['csrftoken'] user = User.objects.create(username='******') user.set_password('password') user.save() # Perform a login response = client.post('http://testserver/auth/', json={ 'username': '******', 'password': '******' }, headers={'X-CSRFToken': csrftoken}) assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = { 'username': '******' } assert response.json() == expected # Confirm session is authenticated response = client.get('http://testserver/auth/') assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json' expected = { 'username': '******' } assert response.json() == expected