Example #1
0
def get_mock():
    ysc = youtube_status_code
    yu = youtube_url
    yc = youtube_cookies
    yt = youtube_text
    yh = youtube_headers
    yosc = youtube_oembed_status_code
    you = youtube_oembed_url
    yoh = youtube_oembed_headers
    yot = youtube_oembed_text

    mock_obj_1 = Mock()
    mock_obj_1.status_code = ysc
    mock_obj_1.url = yu
    mock_obj_1.headers = yh
    mock_obj_1.cookies = yc
    mock_obj_1.text = yt
    mock_obj_1.json = lambda: json.loads(mock_obj_1.text)

    mock_obj_2 = Mock()
    mock_obj_2.status_code = 200
    mock_obj_2.url = you
    mock_obj_2.headers = yoh
    mock_obj_2.text = yot
    mock_obj_2.json = lambda: json.loads(mock_obj_2.text)

    return [mock_obj_1, mock_obj_1, mock_obj_2]
Example #2
0
 def mock_response(self, content, status_code=200, bad_json=False):
     mock = Mock(spec=requests.Response)
     mock.content = content
     mock.ok = status_code >= 200 and status_code < 300
     mock.status_code = status_code
     mock.iter_content = lambda size: mock.content
     if bad_json:
         mock.json = self._raise(ValueError)
     else:
         mock.json = lambda: json.loads(mock.content or '""')
     mock.raise_for_status = lambda: None
     return mock
Example #3
0
def default_args():
    args = Mock()
    args.conf_file = ".lamvery.yml"
    args.alias = "foo"
    args.version = "1"
    args.json = '{"foo": "bar"}'
    return args
Example #4
0
 def setup_mock_options(cls):
     """set up to get a mock options object."""
     mock_options = Mock(
         spec=[
             "json",
             "bindings",
             "open_browser",
             "shards",
             "cluster",
             "health_check_interval_seconds",
             "batch_size",
             "max_per_shard_failures",
             "max_total_failures",
             "restart_threshold",
             "watch_secs",
         ]
     )
     mock_options.json = False
     mock_options.bindings = {}
     mock_options.open_browser = False
     mock_options.shards = None
     mock_options.cluster = None
     mock_options.health_check_interval_seconds = 3
     mock_options.batch_size = 5
     mock_options.max_per_shard_failures = 0
     mock_options.max_total_failures = 0
     mock_options.restart_threshold = 30
     mock_options.watch_secs = 30
     mock_options.disable_all_hooks_reason = None
     return mock_options
Example #5
0
class SessionResourceTestCase(TestCase):
    def setUp(self):
        self.schema_url = "/schema"

        self.response = Mock()
        self.response.headers = {"content-type": "application/json; profile=%s" % self.schema_url}

        self.session = Session()

        patch.object(self.session, "request").start()
        self.session.request.return_value = self.response

    def tearDown(self):
        patch.stopall()

    @patch("pluct.session.Resource.from_response")
    @patch("pluct.session.LazySchema")
    def test_creates_resource_from_response(self, LazySchema, from_response):
        LazySchema.return_value = "fake schema"

        self.session.resource("/")

        LazySchema.assert_called_with(href=self.schema_url, session=self.session)

        from_response.assert_called_with(response=self.response, session=self.session, schema="fake schema")

    @patch("pluct.session.Schema")
    def test_creates_schema_from_response(self, Schema):
        self.session.schema("/")
        Schema.assert_called_with("/", raw_schema=self.response.json(), session=self.session)
    def test_load_post(self, RequestsGetMock):

        # set up a mock response with stubbed json to simulate the API
        def read_post_json():
            with open(os.path.join(os.path.dirname(__file__), "data", "post.json")) as post_json_file:
                return json.load(post_json_file)

        mock_response = Mock(Response)
        mock_response.ok = True
        mock_response.text = "some text"
        mock_response.json = read_post_json

        RequestsGetMock.return_value = mock_response

        # call we're testing
        post = self.loader.load_post(1)

        # some validations
        self.assertIsInstance(post, Post)
        self.assertEqual(post.wp_id, 1)
        self.assertEqual(post.title, "This is a Test Post")
        self.assertEqual(post.author.name, "testauthor")
        self.assertEqual(post.categories.first().name, "News")
        self.assertEqual(post.tags.first().name, "Testing")
        self.assertEqual(post.attachments.first().url, "https://test.local/testpost.jpg")
Example #7
0
    def test_3login_flow(self):
        ver_code_of_last_user, last_uid = DBSession.query(User.ver_code, User.id).all()[-1]
        self.assert_(ver_code_of_last_user, "Wrong order of tests")
        req = DummyRequest(
            path="linkedin_confirm/%s" % ver_code_of_last_user,
            matchdict={"code": ver_code_of_last_user},
            user=self.founder,
        )
        auth_uids = []
        confirm_acc.remember = lambda x, y: auth_uids.append(y)
        ret = confirm_acc.linkedin_confirm_view(req)
        self.assert_(last_uid in auth_uids, "User should be logged in")
        self.assert_(isinstance(ret, HTTPFound), "Should redirect to linkedin")

        # now test the linkedin return but mock out all the linkedin credential checks
        req2 = Mock()
        req2.params = {"code": "test"}
        req2.authenticated_userid = last_uid
        login.get_oauth_flow_linkedin = Mock()
        login.requests = Mock()
        linkedin_user_resp = Mock()
        linkedin_email = "testing2linkeding@f.com"
        linkedin_user_resp.json = {"id": "dummyLinkedinID", "emailAddress": linkedin_email}
        login.requests.get = lambda *x, **k: linkedin_user_resp
        login.check_csrf_token = Mock()
        # end of mocks

        self.assert_(self.get_linkedin_email_db(last_uid) != linkedin_email, "Linkedin email should not be set yet")
        ret = login.oauthcallback_view(req2)
        # oauth callback view calls complete_confirm_acc
        self.assert_(isinstance(ret, HTTPFound), "Should redirect to profile")
        self.assert_(
            self.get_linkedin_email_db(last_uid) == linkedin_email,
            "Linkedin email should be set by complete_confirm_acc",
        )
Example #8
0
def test_box_response_properties_pass_through_to_network_response_properties():
    mock_network_response = Mock(DefaultNetworkResponse)
    box_result = BoxResponse(mock_network_response)
    assert box_result.json() == mock_network_response.json()
    assert box_result.content == mock_network_response.content
    assert box_result.ok == mock_network_response.ok
    assert box_result.status_code == mock_network_response.status_code
    assert box_result.network_response == mock_network_response
Example #9
0
def client_credentials_response():
    """Response after Client Credentials Access Request."""
    mock_response = Mock(status_code=http.STATUS_OK)

    response_json = {"access_token": ACCESS_TOKEN, "expires_in": EXPIRES_IN_SECONDS, "scope": SCOPES_STRING}

    mock_response.json = Mock(return_value=response_json)
    return mock_response
Example #10
0
 def patch_requests(self, requests_get, status_code=200):
     requests_json = Mock()
     requests_json.json = lambda: self.sample_items
     requests_json.status_code = status_code
     if status_code != 200:
         requests_json.content = "Some error body"
     requests_get.return_value = requests_json
     return requests_get
Example #11
0
    def mock_get_json_asset(self, asset_file):
        """Mock requests.get result.json with contents of asset_file"""
        get_mock = Mock()

        with open(self.asset_path(asset_file), "r") as f:
            get_mock.json = Mock(return_value=json.load(f))

        requests.get = Mock(return_value=get_mock)
    def test_process_ubersmith_response(self):
        response = Mock(status_code=200, headers={"content-type": "application/json"})

        json_data = {"client_id": "1", "first": "Rick", "last": "Sanchez", "company": "Wubba lubba dub dub!"}

        response.json = Mock(return_value=a_response_data(data=json_data))

        self.assertDictEqual(json_data, UbersmithRequest.process_ubersmith_response(response))
 def setup_mock_options(cls):
     """set up to get a mock options object."""
     mock_options = Mock()
     mock_options.open_browser = False
     mock_options.shards = None
     mock_options.cluster = None
     mock_options.json = False
     return mock_options
 def test_find_by_name_invalid_collector(self):
     error_response = {"error": "Metric Collector '{}' not found.".format(self.subject.name)}
     response = Mock()
     response.json = Mock(return_value=error_response)
     with patch.object(MetricCollectorDetails, "request") as metric_collector_details_request:
         metric_collector_details_request.side_effect = KalibroClientRequestError(response)
         MetricCollectorDetails.find_by_name(self.subject.name)
         metric_collector_details_request.assert_called_once
Example #15
0
def get_mock_no_oembed():
    mock = Mock()
    mock.status_code = youtube_status_code
    mock.url = youtube_url
    mock.cookies = youtube_cookies
    mock.text = "youtube_text"
    mock.json = lambda: json.loads(mock.text)
    return [mock]
Example #16
0
def simple_500_error():
    code = "internal_server_error"

    mock_error = Mock(status_code=http.STATUS_INTERNAL_SERVER_ERROR, headers=http.DEFAULT_CONTENT_HEADERS)

    error_response = {"message": http.ERROR_CODE_DESCRIPTION_DICT[code], "code": code}

    mock_error.json = Mock(return_value=error_response)
    return mock_error
Example #17
0
def simple_503_error():
    code = "service_unavailable"

    mock_error = Mock(status_code=http.STATUS_SERVICE_UNAVAILABLE, headers=http.DEFAULT_CONTENT_HEADERS)

    error_response = {"message": http.ERROR_CODE_DESCRIPTION_DICT[code], "code": code}

    mock_error.json = Mock(return_value=error_response)
    return mock_error
 def test_find_when_it_does_not_find_anything(self):
     date_str = dateutil.parser.parse("2015-07-05T22:16:18+00:00")
     subject = IdentifiedBase(id=1, attribute="attributes", created_at=date_str, updated_at=date_str)
     response = Mock()
     response.json = Mock(return_value={"errors": ["Couldn't find object"]})
     with patch.object(IdentifiedBase, "request") as mock:
         mock.side_effect = KalibroClientRequestError(response)
         IdentifiedBase.find(subject.id)
         mock.assert_called_once_with(":id", params={"id": (subject.id)}, method="get")
Example #19
0
def simple_401_error():
    code = "unauthorized"

    mock_error = Mock(status_code=http.STATUS_UNAUTHORIZED, headers=http.DEFAULT_CONTENT_HEADERS)

    error_response = {"message": http.ERROR_CODE_DESCRIPTION_DICT[code], "code": code}

    mock_error.json = Mock(return_value=error_response)
    return mock_error
Example #20
0
 def setup_mock_options(cls):
     """set up to get a mock options object."""
     mock_options = Mock()
     mock_options.json = False
     mock_options.bindings = {}
     mock_options.open_browser = False
     mock_options.cluster = None
     mock_options.wait_until = "RUNNING"  # or 'FINISHED' for other tests
     return mock_options
Example #21
0
    def set_rpc_error_response(self, error, id=None):
        response = Mock()
        response.status_code = 200

        data = self.make_response_data(result=None, id=id)
        data.error = error
        response.json = data

        self.response = response
    def test_geocode_zeroresults(self):
        response = Mock()
        response.status_code = 200
        response.json = Mock(return_value={"results": [], "status": "ZERO_RESULTS"})
        get = Mock(return_value=response)

        with self.patch("get", get):
            func = geocode.GeoCodeService().geocode
            error = geocode.ZeroResuls
            self.assertRaises(error, func, "query")
def mock_response(content):
    """Mock of requests.get()."""
    response = Mock()
    response.content = content

    def mock_response_json():
        return json.loads(content)

    response.json = mock_response_json
    return response
Example #24
0
 def setup_mock_options(cls):
     """set up to get a mock options object."""
     mock_options = Mock()
     mock_options.env = None
     mock_options.json = False
     mock_options.bindings = {}
     mock_options.open_browser = False
     mock_options.rename_from = None
     mock_options.cluster = None
     return mock_options
Example #25
0
    def test_vimeo_request_basic(self, mock_request):
        mock_response = Mock()
        mock_request.return_value = mock_response
        response = vimeo._vimeo_request("method", "GET", mydata="blah")

        mock_request.assert_called_with(
            "GET", "http://vimeo.com/api/rest/v2?method=method", auth=ANY, data={"mydata": "blah", "format": "json"}
        )
        mock_response.json.assert_called_with()
        eq_(mock_response.json(), response)
Example #26
0
def test_should_raise_if_error_processing_response():
    response = Mock()
    response.json = Mock()
    response.json.side_effect = ValueError

    with patch("requests.get") as mock_get, pytest.raises(discovery.PyEmbedDiscoveryError):
        mock_get.return_value = response

        discoverer = discovery.UrlDiscoverer("http://example.com/providers.json")
        discoverer.get_oembed_urls("http://example.com/simple/123")
    def test_isConvertibleTo(self):
        target_type = Mock()
        target_type.json = Mock(return_value="json value")
        jvm_type = Mock()
        self.check._jvm.org.apache.spark.sql.types.DataType.fromJson = Mock(return_value=jvm_type)

        self.check.isConvertibleTo(self.COLUMN_NAME, target_type)

        target_type.json.assert_called()
        self.check._jvm.org.apache.spark.sql.types.DataType.fromJson.assert_called_with("json value")
        self.jvmCheck.isConvertibleTo.assert_called_with(self.COLUMN_NAME, jvm_type)
    def test_rtm_start(self, mock_connect_ws, mock_post):
        mock_response = Mock()
        mock_response.json = lambda: succeed({"foo": "bar"})
        mock_post.return_value = succeed(mock_response)

        mock_connect_ws.return_value = succeed("dummy return value")

        _, r = yield self.mk_relay()
        resp = yield r.rtm_start("token")
        self.assertEqual(resp, "dummy return value")
        mock_connect_ws.assert_called_with({"foo": "bar"})
Example #29
0
    def test_oembed_handles_jsonp_callbacks(self, registry):
        resource = Mock()
        resource.json = '{"foo": "bar"}'
        provider = Mock()
        provider.expose = True
        provider.get_resource.return_value = resource
        registry.match.return_value = provider

        self.request.GET = {"url": "foo", "callback": "acallback"}
        response = oembed(self.request)
        self.assertEqual('acallback({"foo": "bar"});', response.content)
Example #30
0
 def setup_mock_options(cls):
     """set up to get a mock options object."""
     mock_options = Mock()
     mock_options.open_browser = False
     mock_options.shards = None
     mock_options.cluster = None
     mock_options.json = False
     mock_options.batch_size = None
     mock_options.max_total_failures = 1
     mock_options.disable_all_hooks = False
     return mock_options