예제 #1
0
def test_bad_token_forbidden(settings, live_server):
    client = RequestsClient()
    token = secrets.token_hex(20)
    response = client.get(f"{live_server.url}",
                          headers={"Authorization": f"Token {token}"})
    print(f"headers: {response.request.headers}")
    assert response.status_code == 401
예제 #2
0
 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)
예제 #3
0
def test_token_user_unauthorized(settings, live_server, user):
    client = RequestsClient()
    response = client.get(
        f"{live_server.url}",
        headers={"Authorization": f"Token {user.auth_token.key}"})
    print(f"headers: {response.request.headers}")
    assert response.status_code == 403
예제 #4
0
    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)
예제 #5
0
    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)
예제 #6
0
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)
예제 #7
0
 def test_get_events_by_actor_id(self):
     client = RequestsClient()
     for ro in self.test_2:
         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['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'])
예제 #8
0
    def test_get_article(self):

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

        client = RequestsClient()
        response = client.get(
            'http://127.0.0.1:8000/api/v1/articles/100/?format=json')
예제 #9
0
    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)

        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']
        })
예제 #10
0
    def setUp(self):
        with open("./resources/tests/cfg/test_cash_data.config",
                  "r") as cash_cfg:
            test_data = cash_cfg.read()

        self.investor_test = InvestorUser.objects.create_user(
            username='******', password='******')
        self.cash_test_data = json.loads(test_data)

        self.cash_test_data_1 = self.cash_test_data.get('cash_record_1')
        self.cash_test_data_2 = self.cash_test_data.get('cash_record_2')

        self.cash_test_obj_1 = Cash.objects.create(owner=self.investor_test,
                                                   **self.cash_test_data_1)
        self.cash_test_obj_2 = Cash.objects.create(owner=self.investor_test,
                                                   **self.cash_test_data_2)

        self.client = RequestsClient()
        response = self.client.post('http://127.0.0.1:8000/api/v1/auth/token',
                                    json={
                                        'username': '******',
                                        'password': '******'
                                    })
        content = json.loads(response.content.decode('utf-8'))
        self.token = content.get('token')
예제 #11
0
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)
예제 #12
0
 def test_answer(self):
     print('user score befor answer:',
           CustomUser.objects.get(pk=1).score)  #user score is 0
     self.client = RequestsClient(
     )  #set Apiclient to request client(because to set headers)
     headers = {'userId': '1', 'token': 'sample'}  #set headers
     data = {
         'answers': [{
             'cycle_question_id': '1',
             'data': [{
                 'question': '1',
                 'answer': '3'
             }]
         }]
     }
     response = self.client.post(
         'http://localhost:8000/cinemalog/api/answer',
         json=data,
         headers=headers)
     self.assertEqual(response.status_code,
                      status.HTTP_201_CREATED)  #201: #register answer
     print('user score after answer:',
           CustomUser.objects.get(pk=1).score)  #user score updated
     self.assertEqual(CustomUser.objects.get(pk=1).score,
                      -2)  #check user score
예제 #13
0
 def test_plans(self):
     self.client = RequestsClient(
     )  #set Apiclient to request client(because to set headers)
     headers = {'userId': '1', 'token': 'sample'}  #set headers
     response = self.client.get('http://localhost:8000/cinemalog/api/plans',
                                headers=headers)
     self.assertEqual(response.status_code,
                      status.HTTP_200_OK)  #200:get all record
     self.assertEqual(Plan.objects.count(), 1)  #1 record darim
     response = self.client.get(
         'http://localhost:8000/cinemalog/api/userplan', headers=headers)
     #print(response)
     self.assertEqual(response.status_code,
                      status.HTTP_204_NO_CONTENT)  #user hich plani nadarad
     headers = {
         'userId': '1',
         'token': 'sample',
         'planId': '1'
     }  #set post headers
     response = self.client.post(
         'http://localhost:8000/cinemalog/api/userplan', headers=headers)
     self.assertEqual(response.status_code,
                      status.HTTP_201_CREATED)  #user 1 plan kharid
     response = self.client.post(
         'http://localhost:8000/cinemalog/api/userplan', headers=headers)
     self.assertEqual(response.status_code,
                      status.HTTP_201_CREATED)  #user 2 plan kharid
     response = self.client.post(
         'http://localhost:8000/cinemalog/api/userplan', headers=headers)
     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST
                      )  #user mojaz be kharide bish az 2 plan nist
 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'
 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'
예제 #16
0
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)
예제 #17
0
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)
예제 #18
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)
예제 #19
0
    def test_user_delete(self):
        response = RequestsClient().delete(self.url + '{id}/'.format(
            id=self.user_dakarai_id))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        response = RequestsClient().get(self.url + '{id}/'.format(
            id=self.user_dakarai_id))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
예제 #20
0
    def asserts_user_get_id_result(self, user_id, user_name, user_email):
        response = RequestsClient().get(self.url + '{id}/'.format(id=user_id))
        response_data = response.json()

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response_data['id'], user_id)
        self.assertEqual(response_data['name'], user_name)
        self.assertEqual(response_data['email'], user_email)
예제 #21
0
 def test_fails_if_pin_is_missing(self):
     client = RequestsClient()
     url = reverse('register')
     client.headers.update(
         {'Authorization': 'Bearer {}'.format(self.token)})
     response = client.post('http://testserver{}'.format(url),
                            json={'msisdn': 254763488092})
     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
예제 #22
0
 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')
예제 #23
0
 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
예제 #24
0
 def test_get_schema(self):
     client = RequestsClient()
     client.auth = HTTPBasicAuth(self.username, self.password)
     client.headers.update({'x-test': 'true'})
     res = client.get('http://localhost:8000/schema/')
     self.assertEqual(res.status_code, 200)
     self.assertEqual(res.headers['Content-Type'],
                      "application/coreapi+json")
예제 #25
0
 def test_get_with_requests(self):
     client = RequestsClient()
     response = client.get('http://testserver/api/climb-records/',
                           cookies={
                               'sessionid':
                               self.client.cookies['sessionid'].coded_value
                           })
     self.assertEqual(response.status_code, 200)
 def testInValidAuthCase(self):
     client = RequestsClient()
     response = client.post('http://127.0.0.1:8180/api/v1/rfidAuth/',
                            data={
                                'rfid': '99',
                                'device': str(self.device.identifier)
                            })
     assert response.status_code == 404
예제 #27
0
    def test_get_all_patient_recommendations(self):
        client = RequestsClient()
        response = client.get('%s%s' %
                              (self.live_server_url, '/patientguidelines/'))
        self.assertEquals(response.status_code, 200)

        json = response.json()
        self.assertEquals(json['count'], 50)
예제 #28
0
    def test_fail_not_logged(self):

        client = RequestsClient()

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

        assert r.status_code != 200
예제 #29
0
 def test_get_docs(self):
     client = RequestsClient()
     client.auth = HTTPBasicAuth(self.username, self.password)
     client.headers.update({'x-test': 'true'})
     res = client.get('http://localhost:8000/docs/')
     self.assertEqual(res.status_code, 200)
     self.assertEqual(res.headers['Content-Type'],
                      "text/html; charset=utf-8")
 def setUp(self):
     self.c = RequestsClient()
     self.pre_http = "http://127.0.0.1:8000"
     self.user = UserTrackingProfile.objects.first().user_profile.user
     self.user_profile = UserTrackingProfile.objects.first()
     self.rfid = self.user_profile.user_profile.rfid_tag
     self.exercise_unit = ExerciseUnit.objects.first()
     self.header = {'Authorization': 'Token ' + str(self.user.auth_token)}
예제 #31
0
파일: tests.py 프로젝트: apanik/JobXprss
 def test__when_proper_data_is_given__membership_is_created(self):
     url = 'http://127.0.0.1:8000/api/professional/info_box/'
     client = RequestsClient()
     login = self.client.login(username='******', password='******')
     client.headers.update({'x-test': 'true'})
     response = client.get(url, headers={'api-key': '96d56aceeb9049debeab628ac760aa11'})
     print(response.content)
     self.assertEqual(response.status_code, 200)
 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
 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
예제 #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'] == []
 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
예제 #37
0
 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()
예제 #38
0
    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
    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
예제 #40
0
    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}")
예제 #41
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}")
예제 #42
0
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)