def test_PushoverAPI_sends_complex_message(PushoverAPI):
    """Test sending a more complex message."""
    responses.add_callback(
        responses.POST,
        urljoin(PUSHOVER_API_URL, 'messages.json'),
        callback=messages_callback,
        content_type='application/json'
    )
    resp = PushoverAPI.send_message(
        TEST_USER,
        TEST_MESSAGE,
        device=TEST_DEVICES[0],
        title=TEST_TITLE,
        url=TEST_URL,
        url_title=TEST_URL_TITLE,
        priority=1,
        timestamp=100,
        sound='gamelan'
    )
    # request_body = parse_qs(resp.request.body)
    # assert request_body['token'][0] == TEST_TOKEN
    # assert request_body['user'][0] == TEST_USER
    # assert request_body['device'][0] == TEST_DEVICES[0]
    # assert request_body['title'][0] == TEST_TITLE
    # assert request_body['url'][0] == TEST_URL
    # assert request_body['url_title'][0] == TEST_URL_TITLE
    # assert int(request_body['priority'][0]) == 1
    # assert int(request_body['timestamp'][0]) == 100
    # assert request_body['sound'][0] == 'gamelan'

    assert resp == {
        'status': 1,
        'request': TEST_REQUEST_ID
    }
Exemple #2
0
    def test_create(self):
        def request_handler(request):
            data = json.loads(request.body)
            self.assertEqual(len(data['files']), 2)
            self.assertTrue('test-file-A' in data['files'])

            content = {k: v['content'] for k, v in data['files'].items()}

            self.assertEqual(content['test-file-A'], 'test-content-A')
            self.assertEqual(content['test-file-B'], 'test-content-\u212C')

            status = 200
            headers = {}
            body = json.dumps({
                'html_url': 'https://gist.github.com/gists/1'
                })
            return status, headers, body

        responses.add_callback(
                responses.POST,
                'https://api.github.com/gists',
                callback=request_handler,
                content_type='application/json',
                )

        public = True
        desc = 'test-desc'
        files = {
                'test-file-A': {'content': 'test-content-A'},
                'test-file-B': {'content': 'test-content-\u212C'},
                }

        gist.GistAPI(token='foo').create(desc, files, public)
def test_intent_verified_returns_verified(client):
    responses.add_callback(
        responses.GET, CALLBACK_URL, callback=verify_intent_request_callback
    )

    result = intent_verified("subscribe", TOPIC_URL, CALLBACK_URL, 10)
    assert result is True
 def run():
     responses.add_callback(responses.GET, url, request_callback)
     resp = requests.get(url)
     assert resp.text == "test callback"
     assert resp.status_code == status
     assert 'foo' in resp.headers
     assert resp.headers['foo'] == 'bar'
def set_up_glove(url: str, byt: bytes, change_etag_every: int = 1000):
    # Mock response for the datastore url that returns glove vectors
    responses.add(
            responses.GET,
            url,
            body=byt,
            status=200,
            content_type='application/gzip',
            stream=True,
            headers={'Content-Length': str(len(byt))}
    )

    etags_left = change_etag_every
    etag = "0"
    def head_callback(_):
        """
        Writing this as a callback allows different responses to different HEAD requests.
        In our case, we're going to change the ETag header every `change_etag_every`
        requests, which will allow us to simulate having a new version of the file.
        """
        nonlocal etags_left, etag
        headers = {"ETag": etag}
        # countdown and change ETag
        etags_left -= 1
        if etags_left <= 0:
            etags_left = change_etag_every
            etag = str(int(etag) + 1)
        return (200, headers, "")

    responses.add_callback(
            responses.HEAD,
            url,
            callback=head_callback
    )
Exemple #6
0
    def test_send(self):
        with app.app_context():

            responses.add(responses.GET, '{}/foo1'.format(self.rmq_base_url), status=200)
            self.assertEqual(send('get', 'foo1').status_code, 200)

            #
            # timeouts and other requests errors
            #
            def callback(request):
                raise requests.RequestException('Requests exception')
            responses.add_callback(
                responses.GET, '{}/foo2'.format(self.rmq_base_url), callback=callback,
            )
            with self.assertRaises(InternalServerError):
                send('get', 'foo2')

            #
            # Test non-200 resposes with raise_for_status=True
            #
            responses.add(
                responses.GET, '{}/foo3'.format(self.rmq_base_url), status=400,
            )
            with self.assertRaises(InternalServerError):
                send('get', 'foo3')

            #
            # Test that we return a resposes with raise_for_status=False
            #
            responses.add(
                responses.GET, '{}/foo4'.format(self.rmq_base_url), status=400,
            )
            response = send('get', 'foo4', raise_for_status=False)
            self.assertEqual(response.status_code, 400)
Exemple #7
0
def test_lookup_show():
    responses.add_callback(
        responses.GET, 'http://mock/search',
        callback=search_callback,
        content_type='application/json'
    )

    Trakt.base_url = 'http://mock'

    show = Trakt['search'].lookup('tt0903747', 'imdb')

    assert show.keys == [
        ('tvdb', '81189'),
        ('tmdb', '1396'),
        ('imdb', 'tt0903747'),
        ('tvrage', '18164'),
        ('slug', 'breaking-bad'),
        ('trakt', '1388')
    ]

    assert show.title == "Breaking Bad"
    assert show.year == 2008

    assert sorted(show.images.keys()) == ['fanart', 'poster']
    assert show.overview is not None
    assert show.score is None
    def test_read(self):
        expected_id = 1024
        expected_name = 'Existing entity'
        expected_category = 'Existing category'
        expected_price = Decimal('85.2')

        # Initial data ########################################################
        def request_callback(request):
            payload = {
                'ProductID': expected_id,
                'ProductName': expected_name,
                'Category': expected_category,
                'Price': float(expected_price),
            }

            resp_body = {'value': [payload]}
            headers = {}
            return requests.codes.ok, headers, json.dumps(resp_body)

        responses.add_callback(
            responses.GET, Product.__odata_url__(),
            callback=request_callback,
            content_type='application/json',
        )
        #######################################################################

        product = Service.query(Product).first()
        assert product.id == expected_id
        assert product.name == expected_name
        assert product.category == expected_category
        assert product.price == expected_price
Exemple #9
0
def test_lookup_episode():
    responses.add_callback(
        responses.GET, 'http://mock/search',
        callback=search_callback,
        content_type='application/json'
    )

    Trakt.base_url = 'http://mock'

    episode = Trakt['search'].lookup('tt0959621', 'imdb')

    assert episode.keys == [
        (1, 1),
        ('tvdb', '349232'),
        ('tmdb', '62085'),
        ('imdb', 'tt0959621'),
        ('tvrage', '637041'),
        ('trakt', '73482')
    ]

    assert episode.title == "Pilot"

    assert sorted(episode.images.keys()) == ['screenshot']
    assert episode.overview is not None
    assert episode.score is None

    assert episode.show.keys == [
        ('slug', 'breaking-bad'),
        ('trakt', '1388')
    ]

    assert episode.show.title == "Breaking Bad"
    assert episode.show.year == 2008

    assert sorted(episode.show.images.keys()) == ['fanart', 'poster']
Exemple #10
0
    def test_get_microsegment_changers(self):
        responses.add_callback(
            responses.POST,
            DEFAULT_URL + '/current/general/login',
            callback=login_callback,
            content_type='application/json'
        )

        responses.add_callback(
            responses.GET,
            DEFAULT_URL + '/current/model/GetMicrosegmentChangers',
            callback=get_microsegment_changers_callback,
            content_type='application/json'
        )

        client = Client('username', 'password')
        data = client.model.get_microsegment_changers('2016-01-01', '2016-01-31')
        self.assertEqual(data, [
            {
                'customer_id': '231342',
                'initial': 4,
                'final': 12
            },
            {
                'customer_id': '231342',
                'initial': 3,
                'final': 67
            },
        ])
 def setUp(self):
     self.api = ExternalPayment(self.client_id)
     responses.add_callback(
         responses.POST, re.compile('https?://.*/api/instance-id'),
         callback=self.request_callback,
         content_type='application/json',
     )
Exemple #12
0
def add_callback(base_url):
    responses.add_callback(
        responses.POST,
        re.compile(r'^' + d1_common.url.joinPathElements(base_url, POST_ENDPOINT_RX)),
        callback=_request_callback,
        content_type='',
    )
    def test_process(self):
        def callback(request):
            payload = dict(parse_qsl(request.body))
            success = True
            if payload['request_id'] != 1:
                success = False
            success = all(i in payload for i in ['ext_auth_success_uri', 'ext_auth_fail_uri',
                                                 'request_token', 'instance_id'])
            if success:
                return 200, {}, json.dumps({'status': 'success', 'invoice_id': '0'})
            return 200, {}, json.dumps({'status': 'refused', 'error': 'illegal_params'})

        responses.add_callback(
            responses.POST, re.compile('https?://.*/api/process-external-payment'),
            callback=callback,
            content_type='application/json',
        )

        resp = self.api.process({'request_id': 1,
                                 'ext_auth_success_uri': 'test',
                                 'ext_auth_fail_uri': 'test_fail',
                                 'request_token': 'request_token',
                                 'instance_id': '123',
                                 })
        self.assertEqual(resp.status, 'success')
        self.assertEqual(resp.invoice_id, '0')

        self.assertEqual(len(responses.calls), 2)
def test_get_franchises():
    responses.add_callback(
        responses.GET,
        re.compile('https://www[.]imdb[.]com.*'),
        callback=_request_callback,
        content_type='application/json'
    )
    response = main.app.get_franchises_for_actor(
        {
            'queryStringParameters': {
                'id': '0206359',
                'chunkNum': '0'
            }
        },
        None)
    body_response = json.loads(response['body'])['response']
    assert len(body_response) == 3
    assert body_response[0] == {
        'name': 'El Tonto',
        'char_name': 'The Fool',
        'id': '9013340'
    }
    assert body_response[1] == {
        'name': 'The Lego Movie 2: The Second Part',
        'char_name': 'Benny (voice)',
        'id': '3513498'
    }
def test_hub_subscribe_existing_sub(session):
    user_feed = UserFeed(url=TOPIC_URL)
    db.session.add(user_feed)

    sub = WebSubSubscription(
        topic=TOPIC_URL,
        callback_url=CALLBACK_URL,
        secret="secret",
        lease_seconds=20,
        userfeed=user_feed,
    )
    db.session.add(sub)

    responses.add_callback(
        responses.GET, CALLBACK_URL, callback=verify_intent_request_callback
    )

    hub_subscribe(TOPIC_URL, CALLBACK_URL, 10, "new_secret")

    subs = WebSubSubscription.query.filter_by(topic=TOPIC_URL).all()
    assert len(subs) == 1
    sub = subs[0]
    assert sub.callback_url == CALLBACK_URL
    assert sub.secret == "new_secret"
    assert sub.lease_seconds == 10
Exemple #16
0
def test_import_with_too_many_redirects(client, user):
    csv_url = "http://example.com/file.csv"

    def request_callback(request):
        headers={
            'HTTP/1.1': '301 Moved Permanently',
            'Location': csv_url,
        }
        return (301, headers, '')

    # fetch csv mock response
    responses.add_callback(
        responses.GET,
        csv_url,
        callback=request_callback,
    )


    resp = client.post_json(
        reverse('import-csv-from-link'),
        params=dict(url=csv_url),
        headers=[('Authorization', str('Token %s' % user.auth_token))],
        status=400
    )
    assert 'Exceeded 30 redirects.' == resp.json['url'][0]
    def test_update_with_invalid_mentenanceid(self):
        def request_callback(request):
            method = json.loads(request.body)['method']
            if method == 'maintenance.get':
                return (200, {}, json.dumps(get_response('22')))
            else:
                return (200, {}, json.dumps(update_response('22')))

        responses.add(
            responses.POST, 'https://example.com/zabbix/api_jsonrpc.php',
            body=json.dumps({
                'result': 'authentication_token',
                'id': 1,
                'jsonrpc': '2.0'
            }),
            status=200,
            content_type='application/json'
        )
        m = self._makeOne(
            host='https://example.com',
            user='******',
            password='******')
        maintenance_id = '22'
        responses.reset()
        responses.add_callback(responses.POST, 'https://example.com/zabbix/api_jsonrpc.php',
                     callback=request_callback,
                     content_type='application/json')
        for key in ('maintenanceid', 'name', 'active_since', 'active_till'):
            required_params = {'maintenanceid': maintenance_id,
                               'name': 'test',
                               'active_since': '2004-04-01T12:00+09:00',
                               'active_till': '2014-04-01T12:00+09:00'}
            with self.assertRaises(jsonschema.exceptions.ValidationError):
                required_params.pop(key)
                m.update(required_params)
    def test_dynamic_responses_json(self):
        #这个例子处理json
        def request_callback(request):
            payload = json.loads(request.body)
            headers = {'User-Agent': 'Firefox/12.0'}
            payload.update({'result': 'pass'})
            resp_body = payload
            return (200, headers, json.dumps(resp_body))

        responses.add_callback(responses.POST,
                               'https://nbaplayerprofile.com/api/1/createplayer',
                               callback=request_callback,
                               content_type='application/json')

        request_json_body = {'name': 'Di', 'gender': 'male'}

        resp = requests.post(
            'https://nbaplayerprofile.com/api/1/createplayer',
            json.dumps(request_json_body)
                             )

        self.assertEqual(resp.json(), {"name": "Di", "gender": "male", "result": "pass"})

        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, 'https://nbaplayerprofile.com/api/1/createplayer')
        self.assertEqual(responses.calls[0].response.text, '{"name": "Di", "gender": "male", "result": "pass"}')
        self.assertEqual(responses.calls[0].response.headers['User-Agent'], 'Firefox/12.0')
    def test_import_remote(self):
        repo_name = parse_repo_name(self.workspace.working_dir)
        repo_location = 'http://localhost:8080/repos/%s.json' % repo_name
        responses.add_callback(
            responses.POST,
            'http://localhost:8080/repos.json',
            callback=lambda _: (301, {'Location': repo_location}, ''))

        self.tool.run(
            config=(self.yaml_config, self.config),
            verbose=True,
            clobber=False,
            repo_dir=self.working_dir,
            repo_url=self.workspace.working_dir,
            ini_config=self.ini_config,
            ini_section='app:main',
            update_config=True,
            repo_name=None,
            repo_host='http://localhost:8080')

        cp = ConfigParser()
        cp.read(self.ini_config)
        self.assertEqual(
            cp.get('app:main', 'unicore.content_repo_urls').strip(),
            repo_location)

        with open(self.yaml_config, 'r') as fp:
            data = yaml.safe_load(fp)
            self.assertEqual(data['repositories'], {
                repo_name: self.workspace.working_dir
            })
def test_calc_api():

    def request_callback(request):
        payload = json.loads(request.body)
        resp_body = {'value': sum(payload['numbers'])}
        headers = {'request-id': '728d329e-0e86-11e4-a748-0c84dc037c13'}
        return (200, headers, json.dumps(resp_body))

    responses.add_callback(
        responses.POST, 'http://calc.com/sum',
        callback=request_callback,
        content_type='application/json',
    )

    resp = requests.post(
        'http://calc.com/sum',
        json.dumps({'numbers': [1, 2, 3]}),
        headers={'content-type': 'application/json'},
    )

    assert resp.json() == {'value': 6}

    assert len(responses.calls) == 1
    assert responses.calls[0].request.url == 'http://calc.com/sum'
    assert responses.calls[0].response.text == '{"value": 6}'
    assert (
        responses.calls[0].response.headers['request-id'] ==
        '728d329e-0e86-11e4-a748-0c84dc037c13'
    )
def test_create_name():
    upload_response_body = """
        {"progress": 0,
        "modified": "date.test",
        "error": null,
        "tileset": "testuser.test1",
        "complete": false,
        "owner": "testuser",
        "created": "date.test",
        "id": "id.test",
        "name": "testname"}"""

    def request_callback(request):
        payload = json.loads(request.body)
        assert payload['name'] == "testname"
        return (201, {}, upload_response_body)

    responses.add_callback(
        responses.POST,
        'https://api.mapbox.com/uploads/v1/{0}?access_token={1}'.format(username, access_token),
        match_querystring=True,
        callback=request_callback)

    res = mapbox.Uploader(access_token=access_token).create(
        'http://example.com/test.json', 'testuser.test1', name="testname")
    assert res.status_code == 201
    job = res.json()
    assert job['name'] == "testname"
Exemple #22
0
    def mock_login_response(self, status):
        """ Mock the response of the marketing site login """
        response_url = '{root}/users/{username}'.format(
            root=self.api_root,
            username=self.username
        )

        def request_callback(request):  # pylint: disable=unused-argument
            headers = {
                'location': response_url
            }
            return (302, headers, None)

        responses.add_callback(
            responses.POST,
            '{root}/user'.format(root=self.api_root),
            callback=request_callback,
            content_type='text/html',
        )

        responses.add(
            responses.GET,
            response_url,
            body='',
            content_type='text/html',
            status=status
        )
    def test_send_push_notification(self):

        # Make a mock of the response
        def request_callback(request):
            payload = querystring_parser.parse(request.body)

            if validate_zeropush_payload(payload):
                response_body = {
                    "sent_count": len(payload["device_tokens"][""]),
                    "inactive_tokens": [],
                    "unregistered_tokens": [],
                }
                headers = {"Content-Type": "application/json"}
                return (200, headers, json.dumps(response_body))
            else:
                return (400, {}, {})

        responses.add_callback(
            responses.POST, ZEROPUSH_NOTIFY_URL, callback=request_callback, content_type="application/json"
        )

        zeropush = ZeroPushService({"AUTH_TOKEN": "123123"})
        devices = PushDeviceFactory.create_batch(10)
        send = zeropush.send_push_notification(
            devices,
            "This is the message",
            sound="annoyingSound.mp3",
            badge_number=1,
            payload={"extra": "payload", "in": "notification"},
            expiry=timedelta(days=30),
            category="test",
        )

        assert send is True
Exemple #24
0
def registration(uri):
    """Responses handler registration.

    Registers a handler for a given URI with Responses
    so that it can be intercepted and handed to
    Stack-In-A-Box.

    :param uri: URI used for the base of the HTTP requests

    :returns: n/a
    """

    # log the URI that is used to access the Stack-In-A-Box services
    logger.debug('Registering Stack-In-A-Box at {0} under Python Responses'
                 .format(uri))
    # tell Stack-In-A-Box what URI to match with
    StackInABox.update_uri(uri)

    # Build the regex for the URI and register all HTTP verbs
    # with Responses
    regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri),
                       re.I)
    METHODS = [
        responses.DELETE,
        responses.GET,
        responses.HEAD,
        responses.OPTIONS,
        responses.PATCH,
        responses.POST,
        responses.PUT
    ]
    for method in METHODS:
        responses.add_callback(method,
                               regex,
                               callback=responses_callback)
def test_PushoverAPI_gets_group_info(PushoverAPI):
    """Test getting group info"""
    url_re = re.compile('https://api\.pushover\.net/1/groups/g[a-zA-Z0-9]*\.json')
    responses.add_callback(
        responses.GET,
        url_re,
        callback=groups_callback,
        content_type='application/json'
    )

    resp = PushoverAPI.group_info(TEST_GROUP)
    # request_body = parse_qs(resp.request.body)
    # assert request_body['token'][0] == TEST_TOKEN
    # assert resp.request.path_url.split('/')[-1].split('.')[0] == TEST_GROUP

    assert resp == {
        'status': 1,
        'request': TEST_REQUEST_ID,
        'name': TEST_GROUP_NAME,
        'users': [
            {
                'user': TEST_USER,
                'device': TEST_DEVICES[0],
                'memo': '',
                'disabled': False
            },
            {
                'user': TEST_USER,
                'device': TEST_DEVICES[1],
                'memo': '',
                'disabled': False
            }
        ]
    }
Exemple #26
0
    def test_assignee_search(self):
        responses.add(
            responses.GET,
            'https://example.atlassian.net/rest/api/2/project',
            json=[{'key': 'HSP', 'id': '10000'}],
            match_querystring=False
        )

        def responder(request):
            query = parse_qs(urlparse(request.url).query)
            assert 'HSP' == query['project'][0]
            assert 'bob' == query['query'][0]
            return (200, {}, SAMPLE_USER_SEARCH_RESPONSE)

        responses.add_callback(
            responses.GET,
            'https://example.atlassian.net/rest/api/2/user/assignable/search',
            callback=responder,
            content_type='json',
            match_querystring=False
        )
        org = self.organization
        self.login_as(self.user)

        path = reverse('sentry-extensions-jira-search', args=[org.slug, self.integration.id])

        resp = self.client.get('%s?project=10000&field=assignee&query=bob' % (path,))
        assert resp.status_code == 200
        assert resp.data == [
            {'value': 'deadbeef123', 'label': 'Bobby - [email protected]'}
        ]
def test_PushoverAPI_gets_receipt(PushoverAPI):
    """Test the retrieval of receipt details."""
    url_re = re.compile('https://api\.pushover\.net/1/receipts/r[a-zA-Z0-9]*\.json')
    responses.add_callback(
        responses.GET,
        url_re,
        callback=receipt_callback,
        content_type='application/json'
    )
    resp = PushoverAPI.check_receipt(TEST_RECEIPT_ID)
    # request_body = parse_qs(resp.request.body)
    # assert request_body['token'][0] == TEST_TOKEN
    # assert resp.request.path_url.split('/')[-1].split('.')[0] == TEST_RECEIPT_ID

    assert resp == {
        'status': 1,
        'request': TEST_REQUEST_ID,
        'acknowledged': 1,
        'acknowledged_at': 100,
        'acknowledged_by': TEST_USER,
        'acknowledged_by_device': TEST_DEVICES[0],
        'last_delivered_at': 100,
        'expired': 1,
        'expires_at': 100,
        'called_back': 0,
        'called_back_at': 100
    }
def test_PushoverAPI_sends_multiple_simple_messages(PushoverAPI):
    """Test sending multiple simple messages through one HTTP session."""
    responses.add_callback(
        responses.POST,
        urljoin(PUSHOVER_API_URL, 'messages.json'),
        callback=messages_callback,
        content_type='application/json'
    )

    messages = [{
        'user': TEST_USER,
        'message': TEST_MESSAGE
    }] * 3
    resps = PushoverAPI.send_messages(messages)
    # request_bodies = [parse_qs(resp.request.body) for resp in resps]
    # assert len(resps) == 3
    # assert all(request_body['token'][0] == TEST_TOKEN for request_body in request_bodies)
    # assert all(request_body['user'][0] == TEST_USER for request_body in request_bodies)
    # assert all(request_body['message'][0] == TEST_MESSAGE for request_body in request_bodies)
    # assert all(request_body['html'][0] == 'False' for request_body in request_bodies)

    assert all(resp == {
        'status': 1,
        'request': TEST_REQUEST_ID
    } for resp in resps)
Exemple #29
0
 def httpShouldReturn(self, body=None, callback=None, scheme='http', host='test.wikipedia.org', path='/w/',
                      script='api'):
     url = '{scheme}://{host}{path}{script}.php'.format(scheme=scheme, host=host, path=path, script=script)
     if body is None:
         responses.add_callback(responses.POST, url, callback=callback, content_type='application/json')
     else:
         responses.add(responses.POST, url, body=body, content_type='application/json')
    def test_create(self):
        # Post call ###########################################################
        def request_callback(request):
            payload = json.loads(request.body)

            assert 'OData-Version' in request.headers, 'OData-Version header not in request'

            assert 'ProductID' not in payload, 'Payload contains primary key'
            assert '@odata.type' in payload, 'Payload did not contain @odata.type'

            payload['ProductID'] = 1

            resp_body = payload
            headers = {}
            return requests.codes.created, headers, json.dumps(resp_body)

        responses.add_callback(
            responses.POST, Product.__odata_url__(),
            callback=request_callback,
            content_type='application/json',
        )
        #######################################################################

        new_product = Product()
        new_product.name = u'New Test Product'
        new_product.category = u'Category #1'
        new_product.price = 34.5

        Service.save(new_product)

        assert new_product.id is not None, 'Product.id is not set'
    def test__make_request_ok_with_data(self):
        common = self._build_common()
        request_data = {"test_key": "test_response", "test_key2": False}
        response_data = {"error": False, "a": "test", "b": "test"}

        def request_callback(request):
            assert json.loads(request.body) == request_data
            return 200, {}, json.dumps(response_data)

        responses.add_callback(
            responses.GET,
            f"{self.test_url}/test",
            callback=request_callback,
        )
        assert (FlockApiClient(common)._make_request(
            "/test", "get", False, data=request_data) == response_data)
        responses.add_callback(
            responses.POST,
            f"{self.test_url}/test",
            callback=request_callback,
        )
        assert (FlockApiClient(common)._make_request(
            "/test", "post", True, data=request_data) == response_data)
Exemple #32
0
def get_search_widget_bot(fake_sqlalchemy_engine,
                          monkeypatch,
                          capsys,
                          checkpoint_path=None):
    http_address = activate_responses(fake_sqlalchemy_engine)

    responses.add_callback(
        responses.POST,
        "http://test/help",
        callback=request_callback_help,
        content_type="application/json",
    )

    widget = SearchWidget(
        bbs_search_url=http_address,
        bbs_mysql_engine=fake_sqlalchemy_engine,
        article_saver=ArticleSaver(fake_sqlalchemy_engine),
        checkpoint_path=checkpoint_path,
    )

    bot = SearchWidgetBot(widget, capsys, monkeypatch)

    return bot
    def test_add_attachment(self):

        def add_attachment_callback(request):
            body = json.loads(request.body)
            self.assertDictEqual(
                body,
                {"atln_recordPk": 1,
                 "atln_recordTable": "Content",
                 "attm_name": "test.txt",
                 "contents": 'U29tZSB0ZXh0'})

            return (200, {"Location": "http://localhost:9999/rest/Attachment/2"}, json.dumps({}))

        responses.add_callback(
            responses.POST,
            'http://localhost:9999/rest/repo',
            callback=add_attachment_callback,
            content_type='application/json',
        )

        slims = Slims("testSlims", "http://localhost:9999", "admin", "admin", repo_location="/var/slims/repo")
        content = Record(self.contentValues, slims.slims_api)
        self.assertEqual(2, content.add_attachment("test.txt", b"Some text"))
Exemple #34
0
    def test_retry(self):
        class request_callback:
            def __init__(self):
                self.first_req = True

            def __call__(self, req):
                if self.first_req:
                    self.first_req = False
                    return (200, {}, '{"status":"OVER_QUERY_LIMIT"}')
                return (200, {}, '{"status":"OK","results":[]}')

        responses.add_callback(
            responses.GET,
            "https://maps.googleapis.com/maps/api/geocode/json",
            content_type='application/json',
            callback=request_callback())

        client = googlemaps.Client(key="AIzaasdf")
        client.geocode("Sesame St.")

        self.assertEqual(2, len(responses.calls))
        self.assertEqual(responses.calls[0].request.url,
                         responses.calls[1].request.url)
Exemple #35
0
def test_change_participation_status(client):
    """Test Client.change_participation_status().

    :param Client client: Client instance with test data.
    """
    calendar_id = "cal_123"
    event_uid = "evt_external_439559854"
    status = "accepted"

    def request_callback(request):
        payload = json.loads(request.body)
        assert payload['status'] == status

        return (202, {}, None)

    responses.add_callback(
        responses.POST,
        url='%s/%s/calendars/%s/events/%s/participation_status' % (settings.API_BASE_URL, settings.API_VERSION, calendar_id, event_uid),
        callback=request_callback,
        content_type='application/json',
    )
    result = client.change_participation_status(calendar_id, event_uid, status)
    assert result is None
def test_query_show():
    responses.add_callback(
        responses.GET, 'http://mock/search/show',
        callback=query_callback,
        content_type='application/json'
    )

    Trakt.base_url = 'http://mock'

    shows = Trakt['search'].query('Breaking Bad', 'show')

    assert [(s.score, (s.title, s.year)) for s in shows] == [
        (6795.639,      ('Breaking Bad', 2008)),
        (1.4921961,     ('Breaking In', 2011)),
        (0.15205674,    ('Talking Bad', 2013)),
        (0.023019673,   ('Good Times, Bad Times', 1990)),
        (0.00541616,    ('Mystery Science Theater 3000', 1988)),
        (0.0043216385,  ('What About Brian', 2006)),
        (0.0027682593,  ('Pinocchio', 2014)),
        (0.0014085078,  ('Benidorm', 2007)),
        (0.000756543,   ('Giant Killing', 2010)),
        (0.0006980828,  ('The Birthday Boys', 2013))
    ]
def test_query_episode():
    responses.add_callback(
        responses.GET, 'http://mock/search/episode',
        callback=query_callback,
        content_type='application/json'
    )

    Trakt.base_url = 'http://mock'

    episodes = Trakt['search'].query('Breaking Bad', 'episode')

    assert [(e.score, (e.pk, e.title), (e.show.title, e.show.year)) for e in episodes] == [
        (120.28289, ((   5,  4),     'Pope Breaks Bad'),            ('Falling Skies', 2011)),
        (23.962301, ((2013, 10),    'Breaking Bad Special'),        ('MythBusters', 2003)),
        (21.605352, ((   2,  4),     "Charlie's Dad Breaks Bad"),   ('Anger Management', 2012)),
        (3.5197084, ((   1,  1),     'Breaking Bad'),               ("The Writers' Room", 2013)),
        (1.7284282, ((  12,  1),     'Breaking Bad Girls'),         ('Bad Girls Club', 2006)),
        (1.4575909, ((   8, 16),    'Bad Crazy'),                   ('How I Met Your Mother', 2005)),
        (1.2199193, ((   5, 16),    'Felina'),                      ('Breaking Bad', 2008)),
        (1.0844237, ((   5, 14),    'Ozymandias'),                  ('Breaking Bad', 2008)),
        (1.0452855, ((   1,  1),     'Pilot'),                      ('Breaking Bad', 2008)),
        (0.97547776, ((  5, 13),    "To'hajiilee"),                 ('Breaking Bad', 2008))
    ]
Exemple #38
0
    def test_issue_search_id(self):
        def responder(request):
            query = parse_qs(urlparse(request.url).query)
            assert 'id="HSP-1"' == query['jql'][0]
            return (200, {}, SAMPLE_SEARCH_RESPONSE)

        responses.add_callback(
            responses.GET,
            'https://example.atlassian.net/rest/api/2/search/',
            callback=responder,
            match_querystring=False)
        org = self.organization
        self.login_as(self.user)

        path = reverse('sentry-extensions-jira-search',
                       args=[org.slug, self.integration.id])

        resp = self.client.get('%s?field=externalIssue&query=HSP-1' % (path, ))
        assert resp.status_code == 200
        assert resp.data == [{
            'label': '(HSP-1) this is a test issue summary',
            'value': 'HSP-1'
        }]
def test_query_movie():
    responses.add_callback(
        responses.GET, 'http://mock/search/movie',
        callback=query_callback,
        content_type='application/json'
    )

    Trakt.base_url = 'http://mock'

    movies = Trakt['search'].query('The Avengers', 'movie')

    assert [(m.score, (m.title, m.year)) for m in movies] == [
        (3419.5627,     ('The Avengers', 2012)),
        (58.450645,     ('Avengers: Age of Ultron', 2015)),
        (54.93378,      ('The Avengers', 1998)),
        (37.166332,     ('Captain America: The First Avenger', 2011)),
        (5.0396857,     ('Captain America: The Winter Soldier', 2014)),
        (1.4125466,     ('Captain America: Civil War', 2016)),
        (1.0787,        ('Ultimate Avengers', 2006)),
        (0.9917594,     ('X-Men Origins: Wolverine', 2009)),
        (0.84162766,    ('The Punisher', 2004)),
        (0.72275203,    ('Avengers Confidential: Black Widow & Punisher', 2014))
    ]
    def test_delete_channel_apps_overflow(self):
        responses.add_callback(responses.POST,
                               'https://api.optimove.net/v3.0/general/login',
                               callback=login_callback,
                               content_type='application/json')

        responses.add_callback(
            responses.POST,
            'https://api.optimove.net/v3.0/integrations/DeleteChannelApps',
            callback=delete_channel_apps_callback,
            content_type='application/json')

        client = Client('username', 'password')
        too_much_channel_apps = []
        for channel_app_id in range(150):
            channel_app = {
                'app_id': channel_app_id,
                'channel_id': random.choice(range(1, 5))
            }
            too_much_channel_apps.append(channel_app)

        self.assertRaises(Exception, client.integrations.delete_channel_apps,
                          too_much_channel_apps)
Exemple #41
0
    def test_replacements(self):
        def request_callback(request):
            headers = {}
            payload = parse_qs(request.body)
            self.assertEqual(payload["text"], ['Hello, <x id="7"></x>!'])
            return (200, headers, json.dumps(DEEPL_RESPONSE))

        machine = self.MACHINE_CLS()
        machine.delete_cache()
        self.mock_languages()
        responses.add_callback(
            responses.POST,
            "https://api.deepl.com/v2/translate",
            callback=request_callback,
        )
        # Fetch from service
        self.assert_translate(
            self.SUPPORTED,
            "Hello, %s!",
            self.EXPECTED_LEN,
            machine=machine,
            unit_args={"flags": "python-format"},
        )
    def test_delete_promotions_overflow(self):
        responses.add_callback(responses.POST,
                               'https://api.optimove.net/v3.0/general/login',
                               callback=login_callback,
                               content_type='application/json')

        responses.add_callback(
            responses.POST,
            'https://api.optimove.net/v3.0/integrations/DeletePromotions',
            callback=delete_promotions_callback,
            content_type='application/json')

        client = Client('username', 'password')
        too_much_promotions = []
        for it in range(150):
            promo_code = ''.join([
                random.choice(string.ascii_uppercase + string.digits)
                for _ in range(5)
            ])
            too_much_promotions.append(promo_code)

        self.assertRaises(Exception, client.integrations.delete_promotions,
                          too_much_promotions)
Exemple #43
0
    def test_customfield_search(self):
        def responder(request):
            query = parse_qs(urlparse(request.url).query)
            assert "cf[0123]" == query["fieldName"][0]
            assert "sp" == query["fieldValue"][0]
            return 200, {}, '{"results": [{"displayName": "<b>Sp</b>rint 1 (1)", "value": "1"}]}'

        responses.add_callback(
            responses.GET,
            "https://example.atlassian.net/rest/api/2/jql/autocompletedata/suggestions",
            callback=responder,
            content_type="application/json",
            match_querystring=False,
        )
        org = self.organization
        self.login_as(self.user)

        path = reverse("sentry-extensions-jira-search",
                       args=[org.slug, self.integration.id])

        resp = self.client.get("%s?field=customfield_0123&query=sp" % (path, ))
        assert resp.status_code == 200
        assert resp.data == [{"label": "Sprint 1 (1)", "value": "1"}]
Exemple #44
0
def test_delete():
    s = utils.session()
    dataset = utils.dataset()

    url = tc.URL(path="datasets/1:updateRecords")
    deletes = [
        tc.record._delete_command(record, primary_key_name="primary_key")
        for record in _records_json
    ]
    snoop: Dict = {}
    responses.add_callback(
        responses.POST,
        str(url),
        partial(
            utils.capture_payload, snoop=snoop, status=200, response_json=_response_json
        ),
    )

    response = tc.record.delete(
        s, dataset, _records_json, primary_key_name="primary_key"
    )
    assert response == _response_json
    assert snoop["payload"] == utils.stringify(deletes)
Exemple #45
0
    def test_check_contact_whatsappable_new_channel_config(self):

        def cb(request):
            self.assertEqual(
                request.headers['Authorization'], 'Bearer foo')
            data = json.loads(request.body)
            self.assertEqual(data, {
                'msisdns': ['+254788383383'],
                'number': '+27000000000',
                'wait': True
            })
            return (200, {}, json.dumps([
                {
                    "msisdn": "+254788383383",
                    "wa_exists": True,
                }
            ]))

        responses.add_callback(
            responses.POST,
            "https://wassup.p16n.org/api/v1/lookups/",
            callback=cb, content_type='application/json',
            match_querystring=True)

        joe = self.create_contact("Joe Biden", "+254788383383")
        check_contact_whatsappable([joe.pk], self.new_style_channel.pk)

        has_whatsapp = joe.values.get(contact_field__key='has_whatsapp')
        self.assertEqual(has_whatsapp.string_value, 'yes')

        one_minute_ago = timezone.now() - timedelta(minutes=1)
        has_whatsapp_timestamp = joe.values.get(
            contact_field__key='has_whatsapp_timestamp')
        self.assertTrue(has_whatsapp_timestamp.datetime_value > one_minute_ago)

        group = get_whatsappable_group(joe.org)
        self.assertEqual(set(group.contacts.all()), set([joe]))
Exemple #46
0
def test_create_configdocs_empty(*args):
    def validating_callback(request):
        # a request that has empty_collection should have no body.
        assert request.body is None
        resp_body = stubs.gen_err_resp(
            message='Validations succeeded',
            sub_error_count=0,
            sub_info_count=0,
            reason='Validation',
            code=200)
        return (201, {}, resp_body)

    responses.add_callback(
        responses.POST,
        'http://shiptest/configdocs/design',
        callback=validating_callback,
        content_type='application/json')

    filename = 'tests/unit/cli/create/sample_yaml/sample.yaml'
    document_data = yaml.dump_all(filename)
    file_list = (filename, )

    # pass data and empty_collection = True - should init with data, but
    # not send the data on invoke
    action = CreateConfigdocs(
        stubs.StubCliContext(),
        collection='design',
        buffer_mode='append',
        empty_collection=True,
        data=document_data,
        filenames=file_list)

    assert action.data == document_data
    assert action.empty_collection == True

    response = action.invoke_and_return_resp()
    assert response.startswith("Configuration documents added.")
def test_lookup_episode():
    responses.add_callback(
        responses.GET, 'http://mock/search/imdb/tt0959621',
        callback=lookup_callback,
        content_type='application/json'
    )

    Trakt.base_url = 'http://mock'

    episode = Trakt['search'].lookup('tt0959621', 'imdb')
    assert episode is not None

    assert episode.keys == [
        (1, 1),
        ('tvdb', '349232'),
        ('tmdb', '62085'),
        ('imdb', 'tt0959621'),
        ('tvrage', '637041'),
        ('trakt', '73482')
    ]

    assert episode.title == "Pilot"

    assert episode.overview is not None
    assert episode.score is None

    assert episode.show.keys == [
        ('tvdb', '81189'),
        ('tmdb', '1396'),
        ('imdb', 'tt0903747'),
        ('tvrage', '18164'),
        ('slug', 'breaking-bad'),
        ('trakt', '1388')
    ]

    assert episode.show.title == "Breaking Bad"
    assert episode.show.year == 2008
Exemple #48
0
    def test_getRemoteBugBatch_pagination(self):
        def issues_callback(request):
            url = urlsplit(request.url)
            base_url = urlunsplit(list(url[:3]) + ["", ""])
            page = int(parse_qs(url.query).get("page", ["1"])[0])
            links = []
            if page != 3:
                links.append('<%s?page=%d>; rel="next"' % (base_url, page + 1))
                links.append('<%s?page=3>; rel="last"' % base_url)
            if page != 1:
                links.append('<%s?page=1>; rel="first"' % base_url)
                links.append('<%s?page=%d>; rel="prev"' % (base_url, page - 1))
            start = (page - 1) * 2
            end = page * 2
            return (
                200, {"Link": ", ".join(links)},
                json.dumps(self.sample_bugs[start:end]))

        responses.add_callback(
            "GET",
            "https://gitlab.com/api/v4/projects/user%2Frepository/issues",
            callback=issues_callback, content_type="application/json")
        tracker = GitLab("https://gitlab.com/user/repository/issues")
        self.assertEqual(
            {bug["iid"]: bug for bug in self.sample_bugs},
            tracker.getRemoteBugBatch(
                [str(bug["iid"]) for bug in self.sample_bugs]))
        expected_urls = [
            "https://gitlab.com/api/v4/projects/user%2Frepository/issues?" +
            "&".join("iids[]=%s" % bug["iid"] for bug in self.sample_bugs),
            "https://gitlab.com/api/v4/projects/user%2Frepository/issues?"
            "page=2",
            "https://gitlab.com/api/v4/projects/user%2Frepository/issues?"
            "page=3",
            ]
        self.assertEqual(
            expected_urls, [call.request.url for call in responses.calls])
    def setUp(self):
        self.ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                             rest_host=test_vars["host"],
                             port=test_vars["port"],
                             tls_port=test_vars["tls_port"],
                             tls=test_vars["tls"],
                             use_binary_protocol=False)

        # Mocked responses
        # without headers
        responses.add(responses.GET,
                      'http://rest.ably.io/channels/channel_name/ch1',
                      body='[{"id": 0}, {"id": 1}]',
                      status=200,
                      content_type='application/json')
        # with headers
        responses.add_callback(
            responses.GET,
            'http://rest.ably.io/channels/channel_name/ch2',
            self.get_response_callback(headers={
                'link':
                '<http://rest.ably.io/channels/channel_name/ch2?page=1>; rel="first",'
                ' <http://rest.ably.io/channels/channel_name/ch2?page=2>; rel="next"'
            },
                                       body='[{"id": 0}, {"id": 1}]',
                                       status=200),
            content_type='application/json')

        # start intercepting requests
        responses.start()

        self.paginated_result = PaginatedResult.paginated_query(
            self.ably.http, 'http://rest.ably.io/channels/channel_name/ch1',
            {}, lambda response: response.to_native())
        self.paginated_result_with_headers = PaginatedResult.paginated_query(
            self.ably.http, 'http://rest.ably.io/channels/channel_name/ch2',
            {}, lambda response: response.to_native())
Exemple #50
0
def test_generate_feeds_max_time():
    max_time = 0.5
    num_feeds = 10

    url = 'http://nopenopenope.nope'

    rss_feed_template = '<link type="application/rss+xml" href="{}" />'
    rss_text, rss_links = [], []

    def request_callback(request):
        time.sleep(2 * max_time / num_feeds)
        return (200, {}, '<?xml version="1.0"?> <rss version="2.0"></rss>')

    for idx in range(num_feeds):
        rss_links.append(url + '/{}.rss'.format(idx))
        rss_text.append(rss_feed_template.format(rss_links[-1]))
        responses.add_callback(responses.GET,
                               rss_links[-1],
                               callback=request_callback)
    html = "<html><head>{}</head><body></body></html>".format(
        '\n'.join(rss_text))
    responses.add(responses.GET, url, body=html, status=200)

    discovered = []
    # Make sure it can raise, but get partial results
    with pytest.raises(TimeoutError):
        for feed in feed_seeker.generate_feed_urls(url, max_time=max_time):
            discovered.append(feed)
    assert len(discovered) > 2  # will probably get 4, but this is fine

    def request_callback(request):
        return (200, {}, '')

    # make sure it doesn't always raise
    url = 'http://yupyupyup.yup'
    responses.add(responses.GET, url, body='', status=200)
    list(feed_seeker.generate_feed_urls(url, max_time=max_time))
Exemple #51
0
    def mock_courses_api(self):
        # Create existing seats to be removed by ingest
        audit_run_type = CourseRunType.objects.get(slug=CourseRunType.AUDIT)
        credit_run_type = CourseRunType.objects.get(
            slug=CourseRunType.CREDIT_VERIFIED_AUDIT)
        verified_run_type = CourseRunType.objects.get(
            slug=CourseRunType.VERIFIED_AUDIT)
        audit_run = CourseRunFactory(title_override='audit',
                                     key='audit/course/run',
                                     type=audit_run_type,
                                     course__partner=self.partner)
        verified_run = CourseRunFactory(title_override='verified',
                                        key='verified/course/run',
                                        type=verified_run_type,
                                        course__partner=self.partner)
        credit_run = CourseRunFactory(title_override='credit',
                                      key='credit/course/run',
                                      type=credit_run_type,
                                      course__partner=self.partner)
        no_currency_run = CourseRunFactory(title_override='no currency',
                                           key='nocurrency/course/run',
                                           type=verified_run_type,
                                           course__partner=self.partner)

        professional_type = SeatTypeFactory.professional()
        SeatFactory(course_run=audit_run, type=professional_type)
        SeatFactory(course_run=verified_run, type=professional_type)
        SeatFactory(course_run=credit_run, type=professional_type)
        SeatFactory(course_run=no_currency_run, type=professional_type)

        bodies = mock_data.ECOMMERCE_API_BODIES
        url = self.api_url + 'courses/'
        responses.add_callback(responses.GET,
                               url,
                               callback=mock_api_callback(url, bodies),
                               content_type=JSON)
        return bodies
Exemple #52
0
def test_mining_text(monkeypatch, capsys, mining_schema_df):
    mining_schema_df = mining_schema_df.drop_duplicates(ignore_index=True)

    responses.add_callback(
        responses.POST,
        "http://test/text",
        callback=request_callback,
        content_type="application/json",
    )

    responses.add_callback(
        responses.POST,
        "http://test/help",
        callback=request_callback_help,
        content_type="application/json",
    )

    mining_schema = MiningSchema()
    mining_schema.add_from_df(mining_schema_df)
    mining_widget = MiningWidget(
        mining_server_url="http://test",
        mining_schema=mining_schema,
    )

    bot = MiningWidgetBot(mining_widget, capsys, monkeypatch)
    bot.set_value("input_text", "HELLO")
    bot.click("mine_text")

    assert len(responses.calls) == 2

    display_objs = bot.display_cached
    assert len(display_objs) == 3  # 1 schema + 1 warning + 1 table_extractions
    assert isinstance(display_objs[0], pd.DataFrame)

    assert display_objs[0].equals(mining_schema_df)
    assert isinstance(display_objs[1], HTML)
    assert display_objs[2].equals(table_extractions)
Exemple #53
0
def test_streams_campaigns_pagination(mocker, test_config, profiles_response,
                                      campaigns_response, page_size):
    mocker.patch(
        "source_amazon_ads.streams.common.SubProfilesStream.page_size",
        page_size)
    profiles_response = json.loads(profiles_response)
    for profile in profiles_response:
        profile["accountInfo"]["type"] = "vendor"
    profiles_response = json.dumps(profiles_response)
    setup_responses(profiles_response=profiles_response)

    source = SourceAmazonAds()
    streams = source.streams(test_config)
    profile_stream = get_stream_by_name(streams, "profiles")
    campaigns_stream = get_stream_by_name(streams,
                                          "sponsored_display_campaigns")
    campaigns = json.loads(campaigns_response)

    def campaigns_paginated_response_cb(request):
        query = urlparse(request.url).query
        query = parse_qs(query)
        start_index, count = (int(query.get(f, [0])[0])
                              for f in ["startIndex", "count"])
        response_body = campaigns[start_index:start_index + count]
        return (200, {}, json.dumps(response_body))

    responses.add_callback(
        responses.GET,
        "https://advertising-api.amazon.com/sd/campaigns",
        content_type="application/json",
        callback=campaigns_paginated_response_cb,
    )
    profile_records = get_all_stream_records(profile_stream)

    campaigns_records = get_all_stream_records(campaigns_stream)
    assert len(campaigns_records) == len(profile_records) * len(
        json.loads(campaigns_response))
def test_upload_directory():
    """Test uploading a directory."""

    src_dir = './testdata'

    # upload a directory

    responses.add_callback(responses.POST,
                           'https://siasky.net/skynet/skyfile',
                           callback=response_callback)

    print('Uploading dir ' + src_dir)
    sialink2 = client.upload_directory(src_dir)
    if SIALINK != sialink2:
        sys.exit('ERROR: expected returned sialink ' + SIALINK +
                 ', received ' + sialink2)
    print('Dir upload successful, sialink: ' + sialink2)

    headers = responses.calls[0].request.headers
    assert headers["Content-Type"].startswith("multipart/form-data;")

    params = responses.calls[0].request.params
    assert params["filename"] == "testdata"

    body = str(responses.calls[0].request.body)
    print(body)
    assert body.find('Content-Disposition: form-data; name="files[]"; \
filename="file1"') != -1
    assert body.find('Content-Disposition: form-data; name="files[]"; \
filename="file3"') != -1
    assert body.find('Content-Disposition: form-data; name="files[]"; \
filename="dir1/file2"') != -1
    # Check a file that shouldn't be there.
    assert body.find('Content-Disposition: form-data; name="files[]"; \
filename="file0"') == -1

    assert len(responses.calls) == 1
Exemple #55
0
    def test_get_microsegment_list(self):
        responses.add_callback(
            responses.POST,
            DEFAULT_URL + '/current/general/login',
            callback=login_callback,
            content_type='application/json'
        )

        responses.add_callback(
            responses.GET,
            DEFAULT_URL + '/current/model/GetMicrosegmentList',
            callback=get_microsegment_list_callback,
            content_type='application/json'
        )

        client = Client('username', 'password')
        data = client.model.get_microsegment_list()
        self.assertEqual(data, {
            1: {
                'name': 'DWag1-Europe-Winner',
                'stage_id': 1,
                'future_value': 870.55,
                'churn_rate': 0.55
            },
            2: {
                'name': 'DWag2-US-Loser',
                'stage_id': 2,
                'future_value': 1065.10,
                'churn_rate': 0.52
            },
            3: {
                'name': 'DWag3-ROW-Winner',
                'stage_id': 2,
                'future_value': 1213.76,
                'churn_rate': 0.57
            }
        })
Exemple #56
0
    def test_get_microsegment_changers_with_attributes(self):
        responses.add_callback(
            responses.POST,
            DEFAULT_URL + '/current/general/login',
            callback=login_callback,
            content_type='application/json'
        )

        responses.add_callback(
            responses.GET,
            DEFAULT_URL + '/current/model/GetMicrosegmentChangers',
            callback=get_microsegment_changers_with_attributes_callback,
            content_type='application/json'
        )

        client = Client('username', 'password')
        data = client.model.get_microsegment_changers('2016-01-01', '2016-01-31', ['Alias', 'Country'], ',')
        self.assertEqual(data, [
            {
                'customer_id': '231342',
                'initial': 4,
                'final': 12,
                'attributes': {
                    'Alias': 'BuddyZZ',
                    'Country': 'UK'
                }
            },
            {
                'customer_id': '231342',
                'initial': 3,
                'final': 67,
                'attributes': {
                    'Alias': 'Player99',
                    'Country': 'US'
                }
            },
        ])
Exemple #57
0
    def test_assignee_search(self):
        responses.add(
            responses.GET,
            "https://jira.example.org/rest/api/2/project",
            json=[{
                "key": "HSP",
                "id": "10000"
            }],
            match_querystring=False,
        )

        def responder(request):
            query = parse_qs(urlparse(request.url).query)
            assert "HSP" == query["project"][0]
            assert "bob" == query["username"][0]
            return (200, {}, EXAMPLE_USER_SEARCH_RESPONSE)

        responses.add_callback(
            responses.GET,
            "https://jira.example.org/rest/api/2/user/assignable/search",
            callback=responder,
            content_type="json",
            match_querystring=False,
        )
        org = self.organization
        self.login_as(self.user)

        path = reverse("sentry-extensions-jiraserver-search",
                       args=[org.slug, self.integration.id])

        resp = self.client.get(
            f"{path}?project=10000&field=assignee&query=bob")
        assert resp.status_code == 200
        assert resp.data == [{
            "value": "bob",
            "label": "Bobby - [email protected] (bob)"
        }]
Exemple #58
0
    def mock_response(self, fail=False):
        def request_callback_get(request):
            headers = {}
            if request.path_url == "/Terminology.svc?wsdl":
                with open(TERMINOLOGY_WDSL, "rb") as handle:
                    return (200, headers, handle.read())
            if request.path_url.startswith("/Terminology.svc?wsdl="):
                suffix = request.path_url[22:]
                with open(TERMINOLOGY_WDSL + "." + suffix, "rb") as handle:
                    return (200, headers, handle.read())
            if request.path_url.startswith("/Terminology.svc?xsd="):
                suffix = request.path_url[21:]
                with open(TERMINOLOGY_WDSL + "." + suffix, "rb") as handle:
                    return (200, headers, handle.read())
            return (500, headers, "")

        def request_callback_post(request):
            headers = {}
            if fail:
                return (500, headers, "")
            if b"GetLanguages" in request.body:
                return (200, headers, TERMINOLOGY_LANGUAGES)
            return (200, headers, TERMINOLOGY_TRANSLATE)

        responses.add_callback(
            responses.GET,
            MST_API_URL,
            callback=request_callback_get,
            content_type="text/xml",
        )
        responses.add_callback(
            responses.POST,
            MST_API_URL,
            callback=request_callback_post,
            content_type="text/xml",
        )
Exemple #59
0
def test_search_for_leads(api_client):
    def request_callback(request):
        assert request.url == 'https://api.close.com/api/v1/lead/?query=name%3Asample'
        return (200, {}, json.dumps({
            'has_more': False,
            'data': [
                {
                    'name': 'Sample Lead',
                    'contacts': [],
                    # Other lead fields omitted for brevity
                }
            ]
        }))

    responses.add_callback(
        responses.GET,
        'https://api.close.com/api/v1/lead/',
        callback=request_callback,
        content_type='application/json',
    )

    resp = api_client.get('lead', params={'query': 'name:sample'})
    assert not resp['has_more']
    assert resp['data'][0]['name'] == 'Sample Lead'
Exemple #60
0
    def test_raises_error_if_refresh_authentication_method_returns_falsy_value(
            self):
        client = FailTokenRefreshClient(token='token',
                                        refresh_token_by_default=True)

        self.first_call = True

        def request_callback(request):
            if self.first_call:
                self.first_call = False
                return (401, {}, '')
            else:
                self.first_call = None
                return (201, {}, '')

        responses.add_callback(
            responses.POST,
            client.test().data,
            callback=request_callback,
            content_type='application/json',
        )

        with self.assertRaises(ClientError):
            client.test().post()