コード例 #1
0
def test_admin_can_view_other_user_detail(settings, live_server):
    settings.PATH_TO_JWT_PUBLIC_KEY = TEST_JWT_PUBLIC_KEY_FILE
    sensor01_token_payload = get_token_payload(authorities=["ROLE_MANAGER"])
    encoded = jwt.encode(sensor01_token_payload, str(PRIVATE_KEY), algorithm="RS256")
    utf8_bytes = encoded.decode("utf-8")
    client = RequestsClient()
    # authenticating with "ROLE_MANAGER" creates user if does not already exist
    response = client.get(
        f"{live_server.url}", headers={"Authorization": f"Bearer {utf8_bytes}"}
    )
    assert response.status_code == 200

    sensor02_token_payload = get_token_payload(authorities=["ROLE_MANAGER"])
    sensor02_token_payload["user_name"] = "sensor02"
    encoded = jwt.encode(sensor02_token_payload, str(PRIVATE_KEY), algorithm="RS256")
    utf8_bytes = encoded.decode("utf-8")
    client = RequestsClient()

    sensor01_user = User.objects.get(username=sensor01_token_payload["user_name"])
    kws = {"pk": sensor01_user.pk}
    kws.update(V1)
    user_detail = reverse("user-detail", kwargs=kws)
    response = client.get(
        f"{live_server.url}{user_detail}",
        headers={"Authorization": f"Bearer {utf8_bytes}"},
    )
    assert response.status_code == 200
コード例 #2
0
def test_token_hidden(settings, live_server):
    settings.PATH_TO_JWT_PUBLIC_KEY = TEST_JWT_PUBLIC_KEY_FILE
    token_payload = get_token_payload(authorities=["ROLE_MANAGER"])
    encoded = jwt.encode(token_payload, str(PRIVATE_KEY), algorithm="RS256")
    utf8_bytes = encoded.decode("utf-8")
    client = RequestsClient()
    # authenticating with "ROLE_MANAGER" creates user if does not already exist
    response = client.get(
        f"{live_server.url}", headers={"Authorization": f"Bearer {utf8_bytes}"}
    )
    assert response.status_code == 200

    sensor01_user = User.objects.get(username=token_payload["user_name"])
    kws = {"pk": sensor01_user.pk}
    kws.update(V1)
    user_detail = reverse("user-detail", kwargs=kws)
    client = RequestsClient()
    response = client.get(
        f"{live_server.url}{user_detail}",
        headers={"Authorization": f"Bearer {utf8_bytes}"},
    )
    assert response.status_code == 200
    assert (
        response.json()["auth_token"]
        == "rest_framework.authentication.TokenAuthentication is not enabled"
    )
コード例 #3
0
 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')
コード例 #4
0
    def test_access_shared_timetables(self):

        Friendship.objects.create(initiating_student=self.student,
                                  receiving_student=self.student3,
                                  accepted=True)

        # Self
        client = RequestsClient()
        client.headers.update(
            {'Authorization': 'Token ' + str(self.token.key)})
        response = client.get('http://testserver/api/timetables/2072452q/')
        self.assertEqual(response.status_code, 200)

        # Shared
        client = RequestsClient()
        client.headers.update(
            {'Authorization': 'Token ' + str(self.token.key)})
        response = client.get('http://testserver/api/timetables/2072452y/')
        self.assertEqual(response.status_code, 200)

        # Not shared
        client = RequestsClient()
        client.headers.update(
            {'Authorization': 'Token ' + str(self.token.key)})
        response = client.get('http://testserver/api/timetables/2072452n/')
        self.assertEqual(response.status_code, 403)

        # Non existent
        client = RequestsClient()
        client.headers.update(
            {'Authorization': 'Token ' + str(self.token.key)})
        response = client.get('http://testserver/api/timetables/2072452z/')
        self.assertEqual(response.status_code, 404)
コード例 #5
0
    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
コード例 #6
0
ファイル: tests.py プロジェクト: hiancdtrsnm/django-challenge
    def test_put_account(self):

        client = RequestsClient()
        r = client.get('http://localhost:8000/api/v1/accounts/',
                       auth=HTTPBasicAuth('testuser', 'testpassword'))

        assert r.status_code == 200

        r = client.get('http://localhost:8000/api/v1/accounts/1',
                       auth=HTTPBasicAuth('testuser', 'testpassword'))

        assert r.status_code == 200

        data = r.json()

        assert data['billing_city'] == 'ee'

        r = client.put('http://localhost:8000/api/v1/accounts/1/',
                       auth=HTTPBasicAuth('testuser', 'testpassword'),
                       json={'billing_city': 'eeeee'})

        assert r.status_code == 200

        data = r.json()

        assert data['billing_city'] == 'eeeee'
コード例 #7
0
class TestGetAuthenticated(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_no_authentication_sent(self):
        response = self.client.get(
            'http://127.0.0.1:8000/users/authenticated/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_wrong_authentication_sent(self):
        self.client.headers.update({"Authorization": "asdf"})
        response = self.client.get(
            'http://127.0.0.1:8000/users/authenticated/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_correct_authentication(self):
        self.client.headers.update({"Authorization": self.admin_token.key})
        response = self.client.get(
            'http://127.0.0.1:8000/users/authenticated/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
コード例 #8
0
ファイル: tests.py プロジェクト: Michail27/calendar_event
 def test_add_event(self):
     url = reverse("login")
     data = {
         "username": self.login,
         "email": self.email,
         "password": self.password
     }
     response = self.client.post(path=url,
                                 data=dumps(data),
                                 content_type="application/json")
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     clint = RequestsClient()
     data = {
         "title": "Abdfghjglkf11",
         "date_start": "2021-02-01T07:25:00Z",
         "date_finish": "2021-02-01T10:25:00Z",
         "reminder": timedelta(seconds=7200),
         "notification": True
     }
     headers = {
         'Authorization': 'Token ' + Token.objects.get(user=self.user).key
     }
     response = clint.get('http://127.0.0.1:8000/event/createevent/',
                          headers=headers)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     response = clint.get('http://127.0.0.1:8000/event/createevent/',
                          headers=headers,
                          data=data)
コード例 #9
0
    def test_create_attendance_record(self):
        factory = APIRequestFactory()

        # Check not marked as attended
        client = RequestsClient()
        client.headers.update(
            {'Authorization': 'Token ' + str(self.token.key)})
        response = client.get(
            'http://testserver/api/timetables/2072452q/?day=2016-12-5')

        self.assertFalse(response.json()[0]['attended'])

        # Add attendance record
        view = AttendanceRecordViewSet.as_view({'post': 'create'})
        beacon_data = {
            'uuid': '123e4567-e89b-12d3-a456-426655440000',
            'major': 1,
            'minor': 1,
            'seen_at_time': dateutil.parser.parse("Dec 5th, 2016 09:00:00")
        }
        request = factory.post('/attendance-records/', beacon_data)
        force_authenticate(request, user=self.user)
        response = view(request)

        self.assertEqual(response.status_code, 201)  # 201 Created

        # Check marked as attended
        client = RequestsClient()
        client.headers.update(
            {'Authorization': 'Token ' + str(self.token.key)})
        response = client.get(
            'http://testserver/api/timetables/2072452q/?day=2016-12-5')

        self.assertTrue(response.json()[0]['attended'])
コード例 #10
0
    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
コード例 #11
0
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)
コード例 #12
0
ファイル: test_viewsets.py プロジェクト: raiabril/iotgrx
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'])
コード例 #13
0
class ApiTest(TestCase):
    '''Unit Testing for URL End Points'''
    def setUp(self):
        self.client = RequestsClient()
        self.response1 = self.client.get('http://localhost/api/articles/')
        self.response2 = self.client.get('http://localhost/api/authors/')
    def testResponseCode(self):
        assert self.response1.status_code == self.response2.status_code == 200
    def testArtilceResponse(self):
        assert True
    def testAuthorResponse(self):
        assert True
コード例 #14
0
class APITest(TestCase):

    def setUp(self):
        self.client = RequestsClient()

    def test_get_token(self):
        client = APIClient()
        response = client.post('/api-token-auth/', {'username': '******', 'password': '******'}, format='json')
        print(response.status_code)
        assert response.status_code == 200

    def test_login_with_token(self):
        # headers={'Authorization': 'de37743763f5c4c62ad0b0fc7e7f945d05cfe14e'}
        response = self.client.post('http://localhost:8000/api-token-auth/',
                                    data={"username": "******", "password": "******"})
        print(response)
        print(response.headers)
        print(response.status_code)
        assert response.status_code == 200

    def test_login_api_with_username(self):
        client = APIClient()
        client.login(username='******', password='******')

    def test_api_root(self):
        response = self.client.get('http://localhost:8000')
        assert response.status_code == 200

    # def test_get_profiles(self):
    #     client = RequestsClient()
    #     response = client.get('http://localhost:8000/profiles/')
    #     assert response.status_code == 200

    def test_get_posts(self):
        response = self.client.get('http://localhost:8000/posts/')
        assert response.status_code == 200

    def test_get_post_comments(self):
        response = self.client.get('http://localhost:8000/post-comments/')
        assert response.status_code == 200

    def test_get_profile_posts(self):
        response = self.client.get('http://localhost:8000/profile-posts/')
        assert response.status_code == 200

    def test_get_profile_statistics(self):
        response = self.client.get('http://localhost:8000/users-statistics/')
        assert response.status_code == 200

    def test_post_post_owner(self):
        client = APIClient()
        client.post('/posts/', {'title': 'new idea', "body": "helooooooooo"}, format='json')
コード例 #15
0
ファイル: views.py プロジェクト: vishal9708/Event-Management
def register_club(request):
	host =  request.META['HTTP_HOST'] 
	url =  'http://'+host+'/api/clubs/create/'
	client = RequestsClient()
	#print request.user
	if request.method=="POST":
		
		club_name = request.POST.get("club_name")
		csrftoken = request.POST.get("csrfmiddlewaretoken")
		city_name = request.POST.get("city");
		locality_name = request.POST.get("locality");
		#print city_name,locality_name
		#client = RequestsClient()

		response = client.post(url, json={
				    'club_name': club_name,
				    'user':request.user.id,
				}, headers={'X-CSRFToken': csrftoken})
		print response.status_code
		js =  response.json()
		#print response.status_code
		u = js['venue']['update']
		if response.status_code == 201:
			c**t = APIRequestFactory()
			nurl = 'http://'+host+u;
			print nurl
			res = client.get(nurl);
			print res
			p =  res.json()
			venue_name = p['venue_name']
			content_type = p['content_type']
			object_id = p['object_id']
			r = client.put(nurl,data={
				'venue_name':venue_name,
				'content_type':content_type,
				'venue_city':city_name,
				'venue_locality':locality_name,
				'object_id':object_id,
				})
			print r
		#token = request.POST.get('csrfmiddlewaretoken')
		#a = factory.post('http://127.0.0.1:8000/api/clubs/create/',{'club_name':club_name},format=json)
		#print response.json()
	cities = City.objects.all();
	locality = client.get("http://127.0.0.1/api/venues/citylocality")
	locality = json.dumps(locality.json())
	#print locality
	context={
	'cities':cities,
	'locality':locality,
	}
	return render(request, "clubs-create.html",context)
コード例 #16
0
class ExerciseUnitSerializerTest(APITestCase):
    """
    Tests the functionality of the SetSerializer.
    """

    fixtures = ['fix.json']

    def setUp(self):
        self.c = RequestsClient()
        self.pre_http = "http://127.0.0.1:8000"
        self.user = UserTrackingProfile.objects.all()[0].user_profile.user
        self.train_unit = TrainUnit.objects.first()
        self.header = {'Authorization': 'Token ' + str(self.user.auth_token)}

    def test_exerciseunit_retrieval(self):
        """
        Test whether list-interface works properly.
        """
        response = self.c.get(self.pre_http + reverse('exerciseunit_list'),
                              headers=self.header)
        self.assertEqual(response.status_code, 200)

    def test_exerciseunit_retrieval_by_trainunit(self):
        """
        Tests whether exerciseunits for a specific trainunit can be retrieved.
        """
        response = self.c.get(
            self.pre_http + reverse('exerciseunit_trainunit_list',
                                    kwargs={'train_unit': self.train_unit.id}),
            headers=self.header)
        content = (json.loads(response.content.decode("utf-8")))
        self.assertEqual(response.status_code, 200)

    def test_exerciseunit_delete(self):
        """
        When an ExerciseUnit is deleted, all corresponding sets must be deleted, too.
        """
        # get reference on a exerciseunit
        test_unit = ExerciseUnit.objects.all()[1]
        test_id = test_unit.id
        # get reference on all sets of the exerciseunit
        set_count_before = len(Set.objects.filter(exercise_unit=test_unit))
        self.assertNotEqual(set_count_before, 0)
        # delete exercise unit
        self.c.delete(
            self.pre_http +
            reverse('exerciseunit_detail', kwargs={'pk': test_unit.id}),
            headers=self.header)
        # check whether exerciseunit and its sets were deleted
        set_count_after = len(Set.objects.filter(exercise_unit=test_unit))
        self.assertEqual(set_count_after, 0)
        self.assertEqual(len(ExerciseUnit.objects.filter(id=test_id)), 0)
コード例 #17
0
    def test_token_access(self):
        url = URL_ROOT + "/api/status/"

        client_no_token = RequestsClient()
        client_invalid_token = RequestsClient()
        client_invalid_token.headers.update(
            {"Authorization": "Bearer 1111aaaa2222oooo"})

        response = client_no_token.get(url)
        self.assertEqual(response.status_code, 401)

        response = client_invalid_token.get(url)
        self.assertEqual(response.status_code, 401)
コード例 #18
0
class ApiTests(TestCase):
    def setUp(self):
        self.client = RequestsClient()
        # Create some dummy data to test upon.
        self.dish1 = Dish(name='dish test 1 filter1', price=12.76)
        self.dish2 = Dish(name='dish test 2 filter2', price=20)
        self.dish3 = Dish(name='dish test 3', price=10.6)

        self.data_list = [
            self.dish1,
            self.dish2,
            self.dish3
        ]

        # Create the three data objects with one hit to database
        Dish.objects.bulk_create(self.data_list)
    
    def test_fetching_all_dishes_when_success(self):
        """
        Test if fetching all data api is workinga and what status code.
        """
        response = self.client.get('http://localhost:8000/api/dishes')
        self.assertEqual(response.status_code, 200)

    def test_fetching_all_dishes_when_fails(self):
        """
        Test what code status is sent when the link was written wrongly
        """
        response = self.client.get('http://localhost:8000/api/dishess')
        self.assertEqual(response.status_code, 404)

    def test_if_data_fitched_contains_the_same_items_as_added(self):
        """
        Test if the data fetched list has the same number of element as what was added.
        """
        response = self.client.get('http://localhost:8000/api/dishes')
        self.assertEqual(len(response.json()), 3)

    def test_if_filter_is_returning_correct_number_of_items(self):
        """
        Test if the filter returns the correct number of items.
        """
        response = self.client.get('http://localhost:8000/api/dishes?filter=true&name=filter')
        self.assertEqual(len(response.json()), 2)

    def test_if_filter_is_returning_item_when_matched_one_results(self):
        """
        Test if the filter returns the the item when name is filtered upon the item name.
        """
        response = self.client.get('http://localhost:8000/api/dishes?filter=true&name=filter1')
        self.assertEqual(response.json()[0]['name'], 'dish test 1 filter1')
コード例 #19
0
    def test_authentication(self):
        client = RequestsClient()

        # 未提供用户认证信息
        response = client.get('http://testserver/test/')
        assert response.status_code == status.HTTP_401_UNAUTHORIZED

        # 提供用户认证信息
        access_token = 'test_access_token'
        response = client.get(
            'http://testserver/test/', headers={'X-BKAPI-JWT': jwt.VALID_JWT, 'X-BKAPI-TOKEN': access_token}
        )
        assert response.status_code == status.HTTP_200_OK
        assert response.json()['access_token'] == access_token
コード例 #20
0
 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')
コード例 #21
0
ファイル: tests.py プロジェクト: ivanzorya/api_migration
class UpdateMigrationWorkLoadTestCase(SetUpTestCase, APITestCase):
    def setUp(self):
        super().setUp()
        self.client = RequestsClient()

    def test_update_migration(self):
        response_migration = self.client.get(
            'http://testserver/api/v1/migrations/1/',
            headers={'Authorization': f'Bearer {self.token}'})
        self.assertEqual(response_migration.status_code, 200)
        data = {'selected_mount_points': 1}
        query = QueryDict('', mutable=True)
        query.update(data)
        response_update_migration = self.client.patch(
            'http://testserver/api/v1/migrations/1/',
            query,
            headers={'Authorization': f'Bearer {self.token}'})
        self.assertEqual(response_update_migration.status_code, 200)
        self.assertIn(bytes(self.mount_point_name_2, encoding='UTF-8'),
                      response_update_migration.content)

    def test_update_work_load(self):
        ip = uuid.uuid4().hex
        data = {'ip': ip}
        query = QueryDict('', mutable=True)
        query.update(data)
        response_update_work_load_error = self.client.patch(
            'http://testserver/api/v1/work_loads/1/',
            query,
            headers={'Authorization': f'Bearer {self.token}'})
        self.assertEqual(response_update_work_load_error.status_code, 400)
        self.assertIn(bytes('''Can't change''', encoding='UTF-8'),
                      response_update_work_load_error.content)
        data = {'credentials': 2}
        query = QueryDict('', mutable=True)
        query.update(data)
        response_update_work_load = self.client.patch(
            'http://testserver/api/v1/work_loads/1/',
            query,
            headers={'Authorization': f'Bearer {self.token}'})
        self.assertEqual(response_update_work_load.status_code, 200)
        self.assertIn(bytes(self.domain_2, encoding='UTF-8'),
                      response_update_work_load.content)
        response_work_load = self.client.get(
            'http://testserver/api/v1/work_loads/1/',
            headers={'Authorization': f'Bearer {self.token}'})
        self.assertIn(bytes(self.ip, encoding='UTF-8'),
                      response_work_load.content)
コード例 #22
0
ファイル: tests.py プロジェクト: littlerest1/SENG3011_Neon
class ReportCase(TestCase):
    def create_report(self):
        article = Article.objects.create(
            url="http://example.com/" + str(self.article_id),
            headline="example",
            publish=parseDatetime("2222-02-02T02:02Z"),
            p_fuzz="D",
            main_text="example text")
        report = Report.objects.create(article=article)
        self.article_id += 1
        return report

    def setUp(self):
        self.article_id = 0

        report = self.create_report()
        ReportEvent.objects.create(
            report=report,
            e_type="D",
            start_date=parseDatetime("2222-02-02T02:02Z"),
            sd_fuzz="D",
            end_date=parseDatetime("2222-02-02T02:02Z"),
            number_affected=10)

        self.factory = APIRequestFactory()
        self.client = RequestsClient()

    def test_create_reports(self):
        self.assertEqual(Report.objects.count(), 1)

    def test_filter_datetime_simple_include(self):
        # use factory to get the response
        response = self.client.get(
            "http://localhost:8000/v0/reports/?start_date=2222-02-02T02:02:00Z&end_date=2222-03-02T02:02:10Z"
        )
        self.assertEqual(response.json()['count'], 1)

    def test_filter_datetime_simple_not_include(self):
        # use factory to get the response
        response = self.client.get(
            "http://localhost:8000/v0/reports/?start_date=2223-02-02T02:02:00Z&end_date=2223-03-02T02:02:10Z"
        )
        self.assertEqual(response.json()['count'], 0)

    def test_not_input_start_date_and_end_date(self):
        # use factory to get the response
        response = self.client.get("http://localhost:8000/v0/reports/")
        self.assertEqual(response.status_code, 400)
コード例 #23
0
    def test_get_category_data(self):

        client = RequestsClient()
        response = client.get('http://127.0.0.1:8000/api/v1/category/')
        print(response.status_code)
        print(type(response.status_code))
        assert response.status_code == 200
コード例 #24
0
 def test_get_request(self):
     client = RequestsClient()
     response = client.get('http://testserver/')
     assert response.status_code == 200
     assert response.headers['Content-Type'] == 'application/json'
     expected = {'method': 'GET', 'query_params': {}}
     assert response.json() == expected
コード例 #25
0
 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'])
コード例 #26
0
    def test_wrong_post_request(self):
        client = RequestsClient()
        res = client.get(BASE_URL + 'weather/')
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.json(), [])
        res = client.post(BASE_URL + 'weather/', json=self.weather4)
        self.assertEqual(res.status_code, 400, 'Id should be a whole number')
        self.assertEqual(res.json()['id'], ['Enter a whole number.'])
        res = client.post(BASE_URL + 'weather/', json=self.weather5)
        self.assertEqual(res.status_code, 400,
                         'Date should be in given format')
        self.assertEqual(res.json()['date'], ['Enter a valid date/time.'])

        res = client.post(BASE_URL + 'weather/', json=self.weather6)
        self.assertEqual(res.status_code, 400,
                         'Latitude should be in given format')
        self.assertEqual(res.json()['lat'], ['Enter a number.'])
        res = client.post(BASE_URL + 'weather/', json=self.weather7)
        self.assertEqual(res.status_code, 400,
                         'longitude should be in given format')
        self.assertEqual(res.json()['lon'], ['Enter a number.'])
        res = client.post(BASE_URL + 'weather/', json=self.weather8)
        self.assertEqual(res.status_code, 400, 'Bad request data')
        self.assertEqual(res.json()['lat'], ['Enter a number.'])
        self.assertEqual(res.json()['lon'], ['Enter a number.'])
        self.assertEqual(res.json()['id'], ['Enter a whole number.'])
        self.assertEqual(res.json()['date'], ['Enter a valid date/time.'])
        res = client.post(BASE_URL + 'weather/', json=self.weather1)
        self.assertEqual(res.status_code, 201)
コード例 #27
0
    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
コード例 #28
0
ファイル: tests.py プロジェクト: rzavarce/TangramTest
    def test_get_article(self):

        url = 'http://127.0.0.1:8000/api/v1/articles/1/'

        client = RequestsClient()
        response = client.get(
            'http://127.0.0.1:8000/api/v1/articles/1/?format=json')
コード例 #29
0
 def test_get_with_headers(self):
     client = RequestsClient()
     response = client.get('http://testserver/headers/', headers={'User-Agent': 'example'})
     assert response.status_code == 200
     assert response.headers['Content-Type'] == 'application/json'
     headers = response.json()['headers']
     assert headers['USER-AGENT'] == 'example'
コード例 #30
0
 def test_case_1():
     """
     Returns 200 .
     """
     client = RequestsClient()
     status_response = client.get('http://testserver/service/')
     assert status_response.status_code == 200
コード例 #31
0
    def test_non_authorizied_access(self):
        """
            Test an unauthorized access to all endpoints

            Note :
                request the endpoints
                checks the response's code

        """
        client = RequestsClient()
        response = client.get(
            'http://127.0.0.1:8000/api/v1.0/output/roadgrade')
        assert response.status_code == 401
        response = client.get(
            'http://127.0.0.1:8000/api/v1.0/output/trustrate')
        assert response.status_code == 401
コード例 #32
0
    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
コード例 #33
0
 def test_get_request_query_params_by_kwarg(self):
     client = RequestsClient()
     response = client.get('http://testserver/', params={'key': 'value'})
     assert response.status_code == 200
     assert response.headers['Content-Type'] == 'application/json'
     expected = {
         'method': 'GET',
         'query_params': {'key': 'value'}
     }
     assert response.json() == expected
コード例 #34
0
ファイル: test_api.py プロジェクト: GNUtn/eventoL
def test_get_event():
    factory = APIRequestFactory()
    client = RequestsClient()
    request = factory.get('/api/events/', format='json')
    url = request.get_raw_uri()
    response = client.get(url)
    assert response.ok
    assert response.status_code == 200

    json = response.json()
    assert json['count'] == 0
    assert json['next'] is None
    assert json['previous'] is None
    assert json['results'] == []
コード例 #35
0
    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
コード例 #36
0
ファイル: test_return_formats.py プロジェクト: basilleaf/opus
    def _one_api_call(self, api_url_base, api_dict, format):
        """Check single api call to see if response is 200.
           api_url_base: a string of api url
           api_dict: a dictionary containing the payload
           format: a return format string that concatenates with api_url_base
        """
        if settings.TEST_GO_LIVE:
            client = requests.Session()
        else:
            client = RequestsClient()

        api_url = api_url_base + format
        payload = api_dict[api_url_base]["payload"]
        print("Testing URL", api_url, "Payload", payload)
        response = client.get(api_url, params=payload)
        # response = client.get("https://tools.pds-rings.seti.org/opus/api/meta/mults/planet.json", params={'target': 'Jupiter'})

        try:
            self.assertEqual(response.status_code, 200)
            # print(response.url)
        except Exception as e:
            # print(response.url)
            raise
コード例 #37
0
ファイル: test_search_api.py プロジェクト: basilleaf/opus
class ApiSearchTests(TestCase, ApiTestHelper):

    # disable error logging and trace output before test
    def setUp(self):
        settings.CACHE_KEY_PREFIX = 'opustest:' + settings.OPUS_SCHEMA_NAME
        self.search_count_threshold = settings.STRINGCHOICE_FULL_SEARCH_COUNT_THRESHOLD
        self.search_time_threshold = settings.STRINGCHOICE_FULL_SEARCH_TIME_THRESHOLD
        self.search_time_threshold2 = settings.STRINGCHOICE_FULL_SEARCH_TIME_THRESHOLD2
        self.search_count_threshold = 1000000000
        self.search_time_threshold = 1000000
        self.search_time_threshold2 = 1000000
        logging.disable(logging.ERROR)
        if settings.TEST_GO_LIVE:
            self.client = requests.Session()
        else:
            self.client = RequestsClient()

    # enable error logging and trace output after test
    def tearDown(self):
        settings.STRINGCHOICE_FULL_SEARCH_COUNT_THRESHOLD = self.search_count_threshold
        settings.STRINGCHOICE_FULL_SEARCH_TIME_THRESHOLD = self.search_time_threshold
        settings.STRINGCHOICE_FULL_SEARCH_TIME_THRESHOLD2 = self.search_time_threshold2
        logging.disable(logging.NOTSET)

    def _get_response(self, url):
        if not settings.TEST_GO_LIVE or settings.TEST_GO_LIVE == "production":
            url = "https://tools.pds-rings.seti.org" + url
        else:
            url = "http://dev.pds-rings.seti.org" + url
        return self.client.get(url)

    def _run_status_equal(self, url, expected):
        print(url)
        response = self._get_response(url)
        self.assertEqual(response.status_code, expected)

    def _run_json_equal(self, url, expected):
        print(url)
        response = self._get_response(url)
        self.assertEqual(response.status_code, 200)
        jdata = json.loads(response.content)
        if 'versions' in jdata:
            del jdata['versions']
        if 'versions' in expected:
            del expected['versions']
        if 'reqno' not in expected:
            if 'reqno' in jdata:
                del jdata['reqno']
        if 'full_search' not in expected:
            if 'full_search' in jdata:
                del jdata['full_search']

        print('Got:')
        print(str(jdata))
        print('Expected:')
        print(str(expected))
        self.assertEqual(expected, jdata)

    def _run_stringsearchchoices_subset(self, url, expected):
        # Ignore any returned choices that aren't in the expected set
        # to handle databases that have more stuff in them than we're expecting
        print(url)
        response = self._get_response(url)
        self.assertEqual(response.status_code, 200)
        jdata = json.loads(response.content)
        if 'versions' in jdata:
            del jdata['versions']
        if 'versions' in expected:
            del expected['versions']
        if 'reqno' not in expected:
            if 'reqno' in jdata:
                del jdata['reqno']
        if 'full_search' not in expected:
            if 'full_search' in jdata:
                del jdata['full_search']
        new_choices = []
        for choice in jdata['choices']:
            if choice in expected['choices']:
                new_choices.append(choice)
        print('Got:')
        print(str(jdata))
        print('Expected:')
        print(str(expected))
        print('Restricted Got:')
        print(new_choices)
        jdata['choices'] = new_choices
        self.assertEqual(expected, jdata)


            ###################################################
            ######### /__api/normalizeinput API TESTS #########
            ###################################################

    def test__api_normalizeinput_empty(self):
        "/api/normalizeinput: empty"
        url = '/opus/__api/normalizeinput.json'
        expected = {}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_bad_slug(self):
        "/api/normalizeinput: bad slug"
        url = '/opus/__api/normalizeinput.json?fredethel=1234'
        self._run_status_equal(url, 404)

    def test__api_normalizeinput_int_empty(self):
        "/api/normalizeinput: integer empty"
        url = '/opus/__api/normalizeinput.json?levels='
        expected = {"levels": ""}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_zero(self):
        "/api/normalizeinput: integer zero"
        url = '/opus/__api/normalizeinput.json?levels=0'
        expected = {"levels": "0"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_neg(self):
        "/api/normalizeinput: integer negative"
        url = '/opus/__api/normalizeinput.json?levels=-1234567890'
        expected = {"levels": "-1234567890"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_pos(self):
        "/api/normalizeinput: integer positive"
        url = '/opus/__api/normalizeinput.json?levels=1234567890'
        expected = {"levels": "1234567890"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_spaces(self):
        "/api/normalizeinput: integer spaces"
        url = '/opus/__api/normalizeinput.json?levels=+1234+'
        expected = {"levels": "1234"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_underscores(self):
        "/api/normalizeinput: integer underscores"
        url = '/opus/__api/normalizeinput.json?levels=_12_34_'
        expected = {"levels": "1234"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_commas(self):
        "/api/normalizeinput: integer commas"
        url = '/opus/__api/normalizeinput.json?levels=,1,2,3,4,'
        expected = {"levels": "1234"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_mixed_delim(self):
        "/api/normalizeinput: integer mixed delimiters"
        url = '/opus/__api/normalizeinput.json?levels=+,1_23_,4+'
        expected = {"levels": "1234"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_bad_val1(self):
        "/api/normalizeinput: integer bad value 1X1"
        url = '/opus/__api/normalizeinput.json?levels=1X1'
        expected = {"levels": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_bad_val2(self):
        "/api/normalizeinput: integer bad value 1.2"
        url = '/opus/__api/normalizeinput.json?levels=1.2'
        expected = {"levels": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_large_val(self):
        "/api/normalizeinput: integer large value 1e1234"
        url = '/opus/__api/normalizeinput.json?levels=1e1234'
        expected = {"levels": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_inf(self):
        "/api/normalizeinput: integer inf"
        url = '/opus/__api/normalizeinput.json?levels=inf'
        expected = {"levels": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_ninf(self):
        "/api/normalizeinput: integer -inf"
        url = '/opus/__api/normalizeinput.json?levels=-inf'
        expected = {"levels": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_nan(self):
        "/api/normalizeinput: integer nan"
        url = '/opus/__api/normalizeinput.json?levels=nan'
        expected = {"levels": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_empty(self):
        "/api/normalizeinput: float empty"
        url = '/opus/__api/normalizeinput.json?rightasc1='
        expected = {"rightasc1": ""}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_zero(self):
        "/api/normalizeinput: float zero"
        url = '/opus/__api/normalizeinput.json?rightasc1=0'
        expected = {"rightasc1": "0.000000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_neg(self):
        "/api/normalizeinput: float negative"
        url = '/opus/__api/normalizeinput.json?rightasc1=-123456'
        expected = {"rightasc1": "-123456.000000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_pos(self):
        "/api/normalizeinput: float positive"
        url = '/opus/__api/normalizeinput.json?rightasc1=567890'
        expected = {"rightasc1": "567890.000000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_spaces(self):
        "/api/normalizeinput: float spaces"
        url = '/opus/__api/normalizeinput.json?rightasc1=+1234+'
        expected = {"rightasc1": "1234.000000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_underscores(self):
        "/api/normalizeinput: float underscores"
        url = '/opus/__api/normalizeinput.json?rightasc1=_12_34_'
        expected = {"rightasc1": "1234.000000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_commas(self):
        "/api/normalizeinput: float commas"
        url = '/opus/__api/normalizeinput.json?rightasc1=,1,2,3,4,'
        expected = {"rightasc1": "1234.000000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_mixed_delim(self):
        "/api/normalizeinput: float mixed delimiters"
        url = '/opus/__api/normalizeinput.json?rightasc1=+,1_23_,4+'
        expected = {"rightasc1": "1234.000000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_exponent1(self):
        "/api/normalizeinput: float mixed delimiters"
        url = '/opus/__api/normalizeinput.json?rightasc1=1.123e12'
        expected = {"rightasc1": "1.123000e+12"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_exponent2(self):
        "/api/normalizeinput: float mixed delimiters"
        url = '/opus/__api/normalizeinput.json?rightasc1=1123000000000'
        expected = {"rightasc1": "1.123000e+12"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_bad_val1(self):
        "/api/normalizeinput: float bad value 1X1"
        url = '/opus/__api/normalizeinput.json?rightasc1=1X1'
        expected = {"rightasc1": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_bad_val2(self):
        "/api/normalizeinput: float bad value 1.22h+1"
        url = '/opus/__api/normalizeinput.json?rightasc1=1.22h+1'
        expected = {"rightasc1": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_large_val(self):
        "/api/normalizeinput: float large value 1e1234"
        url = '/opus/__api/normalizeinput.json?rightasc1=1e1234'
        expected = {"rightasc1": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_inf(self):
        "/api/normalizeinput: float inf"
        url = '/opus/__api/normalizeinput.json?rightasc1=inf'
        expected = {"rightasc1": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_int_ninf(self):
        "/api/normalizeinput: float -inf"
        url = '/opus/__api/normalizeinput.json?rightasc1=-inf'
        expected = {"rightasc1": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_float_nan(self):
        "/api/normalizeinput: float nan"
        url = '/opus/__api/normalizeinput.json?rightasc1=nan'
        expected = {"rightasc1": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_time1(self):
        "/api/normalizeinput: time 2012-01-04T01:02:03.123"
        url = '/opus/__api/normalizeinput.json?time1=2012-01-04T01:02:03.123'
        expected = {"time1": "2012-01-04T01:02:03.123"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_time2(self):
        "/api/normalizeinput: time 2012-01-04T01:02:03"
        url = '/opus/__api/normalizeinput.json?time1=2012-01-04T01:02:03'
        expected = {"time1": "2012-01-04T01:02:03.000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_time3(self):
        "/api/normalizeinput: time 2012-01-04"
        url = '/opus/__api/normalizeinput.json?time1=2012-01-04'
        expected = {"time1": "2012-01-04T00:00:00.000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_time4(self):
        "/api/normalizeinput: time July 4 2001"
        url = '/opus/__api/normalizeinput.json?time1=July+4+2001'
        expected = {"time1": "2001-07-04T00:00:00.000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_time5(self):
        "/api/normalizeinput: time July 4 2001 6:05"
        url = '/opus/__api/normalizeinput.json?time1=July+4+2001+6:05'
        expected = {"time1": "2001-07-04T06:05:00.000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_cassini_orbit_int1(self):
        "/api/normalizeinput: cassini revnoint A"
        url = '/opus/__api/normalizeinput.json?CASSINIrevnoint2=A'
        expected = {"CASSINIrevnoint2": "00A"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_cassini_orbit_int2(self):
        "/api/normalizeinput: cassini revnoint 00A"
        url = '/opus/__api/normalizeinput.json?CASSINIrevnoint1=00A'
        expected = {"CASSINIrevnoint1": "00A"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_cassini_orbit_int3(self):
        "/api/normalizeinput: cassini revnoint 004"
        url = '/opus/__api/normalizeinput.json?CASSINIrevnoint2=004'
        expected = {"CASSINIrevnoint2": "004"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_cassini_orbit_int_bad(self):
        "/api/normalizeinput: cassini revnoint bad value 00D"
        url = '/opus/__api/normalizeinput.json?CASSINIrevnoint1=00D'
        expected = {"CASSINIrevnoint1": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_cassini_sclk1(self):
        "/api/normalizeinput: cassini sclk1 1/1294561143"
        url = '/opus/__api/normalizeinput.json?CASSINIspacecraftclockcount1=1/1294561143'
        expected = {"CASSINIspacecraftclockcount1": "1294561143.000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_cassini_sclk1_bad(self):
        "/api/normalizeinput: cassini sclk1 bad value 2/1294561143"
        url = '/opus/__api/normalizeinput.json?CASSINIspacecraftclockcount1=2/1294561143'
        expected = {"CASSINIspacecraftclockcount1": None}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_cassini_sclk2(self):
        "/api/normalizeinput: cassini sclk2 1/1294561143"
        url = '/opus/__api/normalizeinput.json?CASSINIspacecraftclockcount2=1/1294561143'
        expected = {"CASSINIspacecraftclockcount2": "1294561143.000"}
        self._run_json_equal(url, expected)

    def test__api_normalizeinput_cassini_sclk2_bad(self):
        "/api/normalizeinput: cassini sclk2 bad value 2/1294561143"
        url = '/opus/__api/normalizeinput.json?CASSINIspacecraftclockcount2=2/1294561143'
        expected = {"CASSINIspacecraftclockcount2": None}
        self._run_json_equal(url, expected)


            ########################################################
            ######### /__api/stringsearchchoices API TESTS #########
            ########################################################

    def test__api_stringsearchchoices_bad_slug(self):
        "/api/stringsearchchoices: bad slug"
        url = '/opus/__api/stringsearchchoices/fredethel.json'
        self._run_status_equal(url, 404)

    def test__api_stringsearchchoices_bad_limit(self):
        "/api/stringsearchchoices: bad limit"
        url = '/opus/__api/stringsearchchoices/volumeid.json&limit=0A'
        self._run_status_equal(url, 404)

    def test__api_stringsearchchoices_bad_limit_val_n1(self):
        "/api/stringsearchchoices: bad limit -1"
        url = '/opus/__api/stringsearchchoices/volumeid.json&limit=-1'
        self._run_status_equal(url, 404)

    def test__api_stringsearchchoices_bad_limit_val_0(self):
        "/api/stringsearchchoices: bad limit 0"
        url = '/opus/__api/stringsearchchoices/volumeid.json&limit=0'
        self._run_status_equal(url, 404)

    def test__api_stringsearchchoices_bad_limit_val_1000000000001(self):
        "/api/stringsearchchoices: bad limit 1000000000001"
        url = '/opus/__api/stringsearchchoices/volumeid.json&limit=1000000000001'
        self._run_status_equal(url, 404)

    def test__api_stringsearchchoices_bad_search(self):
        "/api/stringsearchchoices: bad search"
        url = '/opus/__api/stringsearchchoices/volumeid.json?fredethel=2'
        self._run_status_equal(url, 404)

    def test__api_stringsearchchoices_bad_search2(self):
        "/api/stringsearchchoices: bad search2"
        url = '/opus/__api/stringsearchchoices/volumeid.json?missionid=A'
        self._run_status_equal(url, 404)

    def test__api_stringsearchchoices_volumeid_none(self):
        "/api/stringsearchchoices: volumeid none"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=BAD_VOLUME'
        expected = {'choices': [],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_volumeid_GO_0017(self):
        "/api/stringsearchchoices: volumeid GO_0017"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=GO_0017'
        expected = {'choices': ['<b>GO_0017</b>'],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_volumeid_O_0017(self):
        "/api/stringsearchchoices: volumeid O_0017"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=O_0017'
        expected = {'choices': ['G<b>O_0017</b>'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_volumeid_O_0017(self):
        "/api/stringsearchchoices: volumeid O_0017"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=O_0017'
        expected = {'choices': ['G<b>O_0017</b>'],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_volumeid_COISS_2002(self):
        "/api/stringsearchchoices: volumeid COISS_2002"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=COISS_2002'
        expected = {'choices': ['<b>COISS_2002</b>'],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_empty_COISS_2002(self):
        "/api/stringsearchchoices: datasetid empty volumeid COISS_2002"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid='
        expected = {'choices': ['CO-S-ISSNA/ISSWA-2-EDR-V1.0'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_empty2_COISS_2002(self):
        "/api/stringsearchchoices: datasetid empty2 volumeid COISS_2002"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002'
        expected = {'choices': ['CO-S-ISSNA/ISSWA-2-EDR-V1.0'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_begin_COISS_2002(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=CO-S'
        expected = {'choices': ['<b>CO-S</b>-ISSNA/ISSWA-2-EDR-V1.0'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_middle_COISS_2002(self):
        "/api/stringsearchchoices: datasetid ISSWA volumeid COISS_2002"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=ISSWA'
        expected = {'choices': ['CO-S-ISSNA/<b>ISSWA</b>-2-EDR-V1.0'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_end_COISS_2002(self):
        "/api/stringsearchchoices: datasetid V1.0 volumeid COISS_2002"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=V1.0'
        expected = {'choices': ['CO-S-ISSNA/ISSWA-2-EDR-<b>V1.0</b>'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_begins_good(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 begins good"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=CO-S&qtype-datasetid=begins'
        expected = {'choices': ['<b>CO-S</b>-ISSNA/ISSWA-2-EDR-V1.0'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_begins_bad(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 begins bad"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=O-S&qtype-datasetid=begins'
        expected = {'choices': [],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_contains_good(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 contains good"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=ISSNA&qtype-datasetid=contains'
        expected = {'choices': ['CO-S-<b>ISSNA</b>/ISSWA-2-EDR-V1.0'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_contains_bad(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 contains bad"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=ISSNAISSWA&qtype-datasetid=contains'
        expected = {'choices': [],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_ends_good(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 ends good"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=V1.0&qtype-datasetid=ends'
        expected = {'choices': ['CO-S-ISSNA/ISSWA-2-EDR-<b>V1.0</b>'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_ends_bad(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 ends bad"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=O-S&qtype-datasetid=ends'
        expected = {'choices': [],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_matches_good(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 matches good"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=ISSNA&qtype-datasetid=matches'
        expected = {'choices': ['CO-S-<b>ISSNA</b>/ISSWA-2-EDR-V1.0'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_matches_bad(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 matches bad"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=ISSNAX&qtype-datasetid=matches'
        expected = {'choices': [],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_excludes_good(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 excludes good"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=V1&qtype-datasetid=excludes'
        expected = {'choices': [],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_datasetid_COISS_2002_excludes_bad(self):
        "/api/stringsearchchoices: datasetid CO-S volumeid COISS_2002 excludes bad"
        url = '/opus/__api/stringsearchchoices/datasetid.json?volumeid=COISS_2002&datasetid=V1X&qtype-datasetid=excludes'
        expected = {'choices': ['CO-S-ISSNA/ISSWA-2-EDR-V1.0'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_productid_14609_COISS_2002(self):
        "/api/stringsearchchoices: productid 14609 volumeid COISS_2002"
        url = '/opus/__api/stringsearchchoices/productid.json?volumeid=COISS_2002&productid=14609'
        expected = {'choices': ['1_N<b>14609</b>60653.122', '1_N<b>14609</b>60868.118', '1_N<b>14609</b>60908.120', '1_N<b>14609</b>60944.118', '1_N<b>14609</b>60992.120', '1_N<b>14609</b>61026.118', '1_N<b>14609</b>61061.118', '1_N<b>14609</b>61193.118', '1_N<b>14609</b>62279.118', '1_N<b>14609</b>62327.120', '1_N<b>14609</b>62415.121', '1_N<b>14609</b>64003.118', '1_N<b>14609</b>64043.120', '1_N<b>14609</b>65631.118', '1_N<b>14609</b>65679.120', '1_N<b>14609</b>65767.121', '1_N<b>14609</b>66953.122', '1_N<b>14609</b>67168.118', '1_N<b>14609</b>67208.120', '1_N<b>14609</b>67244.118', '1_N<b>14609</b>67292.120', '1_N<b>14609</b>67326.118', '1_N<b>14609</b>67361.118', '1_N<b>14609</b>67493.118', '1_N<b>14609</b>69019.122', '1_N<b>14609</b>69979.122', '1_N<b>14609</b>70939.122', '1_N<b>14609</b>71899.122', '1_N<b>14609</b>73253.122', '1_N<b>14609</b>73468.118', '1_N<b>14609</b>73508.120', '1_N<b>14609</b>73544.118', '1_N<b>14609</b>73592.120', '1_N<b>14609</b>73626.118', '1_N<b>14609</b>73661.118', '1_N<b>14609</b>73793.118', '1_N<b>14609</b>74303.122', '1_N<b>14609</b>74933.122', '1_N<b>14609</b>75548.122', '1_N<b>14609</b>79553.122', '1_N<b>14609</b>79768.118', '1_N<b>14609</b>79808.120', '1_N<b>14609</b>79844.118', '1_N<b>14609</b>79892.120', '1_N<b>14609</b>79926.118', '1_N<b>14609</b>79961.118', '1_N<b>14609</b>80093.118', '1_N<b>14609</b>80638.122', '1_N<b>14609</b>80902.123', '1_N<b>14609</b>80958.125', '1_N<b>14609</b>81222.126', '1_N<b>14609</b>81262.127', '1_N<b>14609</b>81366.128', '1_N<b>14609</b>81733.118', '1_N<b>14609</b>81997.120', '1_N<b>14609</b>82134.118', '1_N<b>14609</b>82398.120', '1_N<b>14609</b>82871.118', '1_N<b>14609</b>83007.120', '1_N<b>14609</b>83208.118', '1_N<b>14609</b>83728.120', '1_N<b>14609</b>84033.118', '1_N<b>14609</b>84297.120', '1_N<b>14609</b>84498.118', '1_N<b>14609</b>84762.120', '1_N<b>14609</b>84899.118', '1_N<b>14609</b>85164.118', '1_N<b>14609</b>85853.122', '1_N<b>14609</b>86068.118', '1_N<b>14609</b>86108.120', '1_N<b>14609</b>86144.118', '1_N<b>14609</b>86192.120', '1_N<b>14609</b>86226.118', '1_N<b>14609</b>86261.118', '1_N<b>14609</b>86393.118', '1_N<b>14609</b>88537.122'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_productid_14609_COISS_2002_limit76(self):
        "/api/stringsearchchoices: productid 14609 volumeid COISS_2002 limit 76"
        url = '/opus/__api/stringsearchchoices/productid.json?volumeid=COISS_2002&productid=14609&limit=76'
        expected = {'choices': ['1_N<b>14609</b>60653.122', '1_N<b>14609</b>60868.118', '1_N<b>14609</b>60908.120', '1_N<b>14609</b>60944.118', '1_N<b>14609</b>60992.120', '1_N<b>14609</b>61026.118', '1_N<b>14609</b>61061.118', '1_N<b>14609</b>61193.118', '1_N<b>14609</b>62279.118', '1_N<b>14609</b>62327.120', '1_N<b>14609</b>62415.121', '1_N<b>14609</b>64003.118', '1_N<b>14609</b>64043.120', '1_N<b>14609</b>65631.118', '1_N<b>14609</b>65679.120', '1_N<b>14609</b>65767.121', '1_N<b>14609</b>66953.122', '1_N<b>14609</b>67168.118', '1_N<b>14609</b>67208.120', '1_N<b>14609</b>67244.118', '1_N<b>14609</b>67292.120', '1_N<b>14609</b>67326.118', '1_N<b>14609</b>67361.118', '1_N<b>14609</b>67493.118', '1_N<b>14609</b>69019.122', '1_N<b>14609</b>69979.122', '1_N<b>14609</b>70939.122', '1_N<b>14609</b>71899.122', '1_N<b>14609</b>73253.122', '1_N<b>14609</b>73468.118', '1_N<b>14609</b>73508.120', '1_N<b>14609</b>73544.118', '1_N<b>14609</b>73592.120', '1_N<b>14609</b>73626.118', '1_N<b>14609</b>73661.118', '1_N<b>14609</b>73793.118', '1_N<b>14609</b>74303.122', '1_N<b>14609</b>74933.122', '1_N<b>14609</b>75548.122', '1_N<b>14609</b>79553.122', '1_N<b>14609</b>79768.118', '1_N<b>14609</b>79808.120', '1_N<b>14609</b>79844.118', '1_N<b>14609</b>79892.120', '1_N<b>14609</b>79926.118', '1_N<b>14609</b>79961.118', '1_N<b>14609</b>80093.118', '1_N<b>14609</b>80638.122', '1_N<b>14609</b>80902.123', '1_N<b>14609</b>80958.125', '1_N<b>14609</b>81222.126', '1_N<b>14609</b>81262.127', '1_N<b>14609</b>81366.128', '1_N<b>14609</b>81733.118', '1_N<b>14609</b>81997.120', '1_N<b>14609</b>82134.118', '1_N<b>14609</b>82398.120', '1_N<b>14609</b>82871.118', '1_N<b>14609</b>83007.120', '1_N<b>14609</b>83208.118', '1_N<b>14609</b>83728.120', '1_N<b>14609</b>84033.118', '1_N<b>14609</b>84297.120', '1_N<b>14609</b>84498.118', '1_N<b>14609</b>84762.120', '1_N<b>14609</b>84899.118', '1_N<b>14609</b>85164.118', '1_N<b>14609</b>85853.122', '1_N<b>14609</b>86068.118', '1_N<b>14609</b>86108.120', '1_N<b>14609</b>86144.118', '1_N<b>14609</b>86192.120', '1_N<b>14609</b>86226.118', '1_N<b>14609</b>86261.118', '1_N<b>14609</b>86393.118', '1_N<b>14609</b>88537.122'],
                    'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_productid_14609_COISS_2002_limit75(self):
        "/api/stringsearchchoices: productid 14609 volumeid COISS_2002 limit 75"
        url = '/opus/__api/stringsearchchoices/productid.json?volumeid=COISS_2002&productid=14609&limit=75'
        expected = {'choices': ['1_N<b>14609</b>60653.122', '1_N<b>14609</b>60868.118', '1_N<b>14609</b>60908.120', '1_N<b>14609</b>60944.118', '1_N<b>14609</b>60992.120', '1_N<b>14609</b>61026.118', '1_N<b>14609</b>61061.118', '1_N<b>14609</b>61193.118', '1_N<b>14609</b>62279.118', '1_N<b>14609</b>62327.120', '1_N<b>14609</b>62415.121', '1_N<b>14609</b>64003.118', '1_N<b>14609</b>64043.120', '1_N<b>14609</b>65631.118', '1_N<b>14609</b>65679.120', '1_N<b>14609</b>65767.121', '1_N<b>14609</b>66953.122', '1_N<b>14609</b>67168.118', '1_N<b>14609</b>67208.120', '1_N<b>14609</b>67244.118', '1_N<b>14609</b>67292.120', '1_N<b>14609</b>67326.118', '1_N<b>14609</b>67361.118', '1_N<b>14609</b>67493.118', '1_N<b>14609</b>69019.122', '1_N<b>14609</b>69979.122', '1_N<b>14609</b>70939.122', '1_N<b>14609</b>71899.122', '1_N<b>14609</b>73253.122', '1_N<b>14609</b>73468.118', '1_N<b>14609</b>73508.120', '1_N<b>14609</b>73544.118', '1_N<b>14609</b>73592.120', '1_N<b>14609</b>73626.118', '1_N<b>14609</b>73661.118', '1_N<b>14609</b>73793.118', '1_N<b>14609</b>74303.122', '1_N<b>14609</b>74933.122', '1_N<b>14609</b>75548.122', '1_N<b>14609</b>79553.122', '1_N<b>14609</b>79768.118', '1_N<b>14609</b>79808.120', '1_N<b>14609</b>79844.118', '1_N<b>14609</b>79892.120', '1_N<b>14609</b>79926.118', '1_N<b>14609</b>79961.118', '1_N<b>14609</b>80093.118', '1_N<b>14609</b>80638.122', '1_N<b>14609</b>80902.123', '1_N<b>14609</b>80958.125', '1_N<b>14609</b>81222.126', '1_N<b>14609</b>81262.127', '1_N<b>14609</b>81366.128', '1_N<b>14609</b>81733.118', '1_N<b>14609</b>81997.120', '1_N<b>14609</b>82134.118', '1_N<b>14609</b>82398.120', '1_N<b>14609</b>82871.118', '1_N<b>14609</b>83007.120', '1_N<b>14609</b>83208.118', '1_N<b>14609</b>83728.120', '1_N<b>14609</b>84033.118', '1_N<b>14609</b>84297.120', '1_N<b>14609</b>84498.118', '1_N<b>14609</b>84762.120', '1_N<b>14609</b>84899.118', '1_N<b>14609</b>85164.118', '1_N<b>14609</b>85853.122', '1_N<b>14609</b>86068.118', '1_N<b>14609</b>86108.120', '1_N<b>14609</b>86144.118', '1_N<b>14609</b>86192.120', '1_N<b>14609</b>86226.118', '1_N<b>14609</b>86261.118', '1_N<b>14609</b>86393.118'],
                    'full_search': False,
                    'truncated_results': True}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_productid_14609_COISS_2002_limit3(self):
        "/api/stringsearchchoices: productid 14609 volumeid COISS_2002 limit 3"
        url = '/opus/__api/stringsearchchoices/productid.json?volumeid=COISS_2002&productid=14609&limit=3'
        expected = {'choices': ['1_N<b>14609</b>60653.122', '1_N<b>14609</b>60868.118', '1_N<b>14609</b>60908.120'],
                    'full_search': False,
                    'truncated_results': True}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_volumeid_002_COISS(self):
        "/api/stringsearchchoices: volumeid 002 instrumentid COISS"
        # The time constraint eliminates COISS_1002 as a result
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=002&instrument=Cassini+ISS&time1=2004-02-06T02:07:06.418'
        expected = {'choices': ['COISS_2<b>002</b>'],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_stringsearchchoices_subset(url, expected)

    def test__api_stringsearchchoices_volumeid_002_COUVIS(self):
        "/api/stringsearchchoices: volumeid 002 instrumentid COUVIS"
        # The time constraint eliminates COUVIS_002x as results
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=002&instrument=Cassini+UVIS&time2=2007-04-05T03:56:00.537'
        expected = {'choices': ['COUVIS_0<b>002</b>'],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_stringsearchchoices_subset(url, expected)

    def test__api_stringsearchchoices_volumeid_002_COISS_bigcache(self):
        "/api/stringsearchchoices: volumeid 002 instrumentid COISS bigcache"
        settings.STRINGCHOICE_FULL_SEARCH_COUNT_THRESHOLD = 1
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=002&instrument=Cassini+ISS'
        expected = {'choices': ['COISS_2<b>002</b>', 'COUVIS_0<b>002</b>'],
                    'full_search': True,
                    'truncated_results': False}
        self._run_stringsearchchoices_subset(url, expected)

    def test__api_stringsearchchoices_volumeid_002_COUVIS_bigcache(self):
        "/api/stringsearchchoices: volumeid 002 instrumentid COUVIS bigcache"
        settings.STRINGCHOICE_FULL_SEARCH_COUNT_THRESHOLD = 1
        # The time constraints eliminate COISS_1002 and COUVIS_002x as results
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=002&instrument=Cassini+UVIS'
        expected = {'choices': ['COISS_2<b>002</b>', 'COUVIS_0<b>002</b>'],
                    'full_search': True,
                    'truncated_results': False}
        self._run_stringsearchchoices_subset(url, expected)

    def test__api_stringsearchchoices_volumeid_002_COISS_timeout(self):
        "/api/stringsearchchoices: volumeid 002 instrumentid COISS timeout"
        settings.STRINGCHOICE_FULL_SEARCH_TIME_THRESHOLD = 1
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=002&instrument=Cassini+ISS'
        expected = {'choices': ['COISS_2<b>002</b>', 'COUVIS_0<b>002</b>'],
                    'full_search': True,
                    'truncated_results': False}
        self._run_stringsearchchoices_subset(url, expected)

    def test__api_stringsearchchoices_volumeid_002_COUVIS_timeout(self):
        "/api/stringsearchchoices: volumeid 002 instrumentid COUVIS timeout"
        settings.STRINGCHOICE_FULL_SEARCH_TIME_THRESHOLD = 1
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=002&instrument=Cassini+UVIS'
        expected = {'choices': ['COISS_2<b>002</b>', 'COUVIS_0<b>002</b>'],
                    'full_search': True,
                    'truncated_results': False}
        self._run_stringsearchchoices_subset(url, expected)

    def test__api_stringsearchchoices_volumeid_O_0017_cache(self):
        "/api/stringsearchchoices: volumeid O_0017 cached reqno"
        # Make sure that reqno isn't cached along with the rest of the result
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=O_0017&reqno=5'
        expected = {'choices': ['G<b>O_0017</b>'],
                    # 'full_search': False,
                    'truncated_results': False,
                    'reqno': 5}
        self._run_json_equal(url, expected)
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=O_0017&reqno=100'
        expected = {'choices': ['G<b>O_0017</b>'],
                    # 'full_search': False,
                    'truncated_results': False,
                    'reqno': 100}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_underscore(self):
        "/api/stringsearchchoices: underscore"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=____'
        expected = {'choices': [],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_percent(self):
        "/api/stringsearchchoices: percent"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=%%'
        expected = {'choices': [],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_lower_case(self):
        "/api/stringsearchchoices: lower_case"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=coiss_2002'
        expected = {'choices': ['<b>COISS_2002</b>'],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_parens(self):
        "/api/stringsearchchoices: parens"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=coiss_)'
        expected = {'choices': [],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_parens2(self):
        "/api/stringsearchchoices: parens 2"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=coiss_()'
        expected = {'choices': [],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)

    def test__api_stringsearchchoices_backslash(self):
        "/api/stringsearchchoices: backslash"
        url = '/opus/__api/stringsearchchoices/volumeid.json?volumeid=\\1'
        expected = {'choices': [],
                    # 'full_search': False,
                    'truncated_results': False}
        self._run_json_equal(url, expected)
コード例 #38
0
    def _collect_vims_image_numbers_for_single_primary_filespec(self, primary_filespec, api_dict):
        """Collect vims image numbers for ONE primary_filespecself.
           return an image_count object to store the numbers
           ex:
           {'co-vims-v1490874598_001_ir': {
                'browse-thumb': 2,
                'browse-small': 2,
                'browse-medium': 2,
                'browse-full': 2,
                'covims-raw': 7,
                'covims-thumb': 2,
                'covims-medium': 2,
                'covims-full': 2}
           }
        """

        if settings.TEST_GO_LIVE:
            client = requests.Session()
        else:
            client = RequestsClient()
            # raise Exception("Test db has no VIMS data")

        format = "json"
        primary_filespec_object = api_dict[primary_filespec]
        api_url = primary_filespec_object["url"] + format
        payload = primary_filespec_object["payload"]
        response = client.get(api_url, params=payload)
        test_url = response.url
        image_count = {}
        response_images = [
                            "browse-thumb",
                            "browse-small",
                            "browse-medium",
                            "browse-full",
                            "covims-raw",
                            "covims-thumb",
                            "covims-medium",
                            "covims-full",
                          ]
        # print(test_url)
        if response.status_code == 200:
            data_object = response.json()["data"]
            # When test db return empty object, we would NOT proceed to count the number of images
            if not data_object and not settings.TEST_GO_LIVE:
                raise Exception("No VIMS data in test db")

            for image_id in primary_filespec_object["images_with_opus_id"]:
                # When image is not fully available in test db, we would NOT proceed to count the number of images
                for image_key in response_images:
                    available_image_in_test_db = data_object[image_id].keys()
                    if image_key not in available_image_in_test_db:
                        raise Exception("VIMS image data is not fully available in test db")

                image_count[image_id] = {
                    "browse-thumb": len(data_object[image_id]["browse-thumb"]),
                    "browse-small": len(data_object[image_id]["browse-small"]),
                    "browse-medium": len(data_object[image_id]["browse-medium"]),
                    "browse-full": len(data_object[image_id]["browse-full"]),
                    "covims-raw": len(data_object[image_id]["covims-raw"]),
                    "covims-thumb": len(data_object[image_id]["covims-thumb"]),
                    "covims-medium": len(data_object[image_id]["covims-medium"]),
                    "covims-full": len(data_object[image_id]["covims-full"]),
                }
            return image_count
        else:
            raise Exception(f"{format}: Error, http status code: {http_status_code}")
コード例 #39
0
ファイル: test_result_counts.py プロジェクト: basilleaf/opus
    def test_api_result_counts_from_csv(self):
        """Result Counts: compare result counts of API calls between csv and live server
           Result counts from live server should always be greater or equal.
           Expected values in csv is obtain from production site on 12/12/18.
           Example of return json:
           {
               "data": [
                   {
                   "result_count": 1411270
                   }
               ]
           }
        """
        api_public = ApiForResultCounts(target=settings.TEST_GO_LIVE)
        if settings.TEST_GO_LIVE:
            client = requests.Session()
        else:
            client = RequestsClient()

        if settings.TEST_GO_LIVE or settings.TEST_RESULT_COUNTS_AGAINST_INTERNAL_DB:
            error_flag = []
            count = 0
            with open(self.filename, "r") as csvfile:

                filereader = csv.reader(csvfile)
                for row in filereader:
                    if len(row) != 3:
                        if len(row) == 0:
                            continue
                        msg = 'Bad results_count line: '+str(row)
                        error_flag.append(msg)
                        msg += ' ==> FAIL!'
                        continue

                    q_str, expected, info = row

                    if q_str.find('#/') == -1:
                        msg = 'Bad results_count line: '+str(row)
                        error_flag.append(msg)
                        msg += ' ==> FAIL!'
                        continue

                    url_hash = q_str.split("#/")[1].strip()
                    api_url = api_public.result_counts_api + url_hash

                    # If current api return has error, we test the next api
                    try:
                        data = json.loads(client.get(api_url).text)
                    except Exception as error:
                        error_flag.append(f"Return error:\n{api_url}")
                        continue

                    result_count = data["data"][0]["result_count"]

                    comparison = '>='
                    if expected[0] == '=':
                        comparison = '='
                        expected = expected[1:]

                    msg = "checking: "+api_url+"\n"
                    msg += f"result: expected {comparison} {expected} :: got {result_count}"

                    if ((comparison == '>=' and
                         int(result_count) < int(expected)) or
                        (comparison == '=' and
                         int(result_count) != int(expected))):
                        error_flag.append(msg)
                        msg += ' ==> FAIL!'
                    else:
                        msg += ' - OK'

                    print(msg)

                    count = count+1

            if error_flag:
                print("============================")
                print("Result counts error summary:")
                print("============================")
                for e in error_flag:
                    print(e+'\n')
                raise Exception("API result counts test failed")
            else:
                print(f"Pass! No result counts failed! \
                      \nActual Number of Tests Run: {count}")