def _happy_path(group, mock_zk, num_members):
    completion_callback = _extract_callback(mock_zk.get_children_async)

    members = []
    for member_id in range(834, 834 + num_members):
        znode_member_id = ActiveKazooGroup.id_to_znode(member_id)
        mock_get_children_result = Mock(name="mock get children async result")
        mock_get_children_result.get = Mock(return_value=[znode_member_id])

        completion_callback(mock_get_children_result)

        mock_zk.get_async.assert_called_with(DEFAULT_PATH + "/" + znode_member_id)

        info_callback = _extract_callback(mock_zk.get_async)

        member_data = "some data for member %s" % member_id

        mock_get_result = Mock(name="mock get async result")
        mock_get_result.get = Mock(return_value=(member_data, Mock(name="znode stat")))
        info_callback(mock_get_result)

        member = Membership(member_id)
        members.append(member)
        assert group._members[member].result() == member_data

    return (frozenset(members), completion_callback)
Example #2
0
    def test_mon_hosts(self):
        hosts = Mock()
        for (name, host) in mon_hosts(("name1", "name2.localdomain", "name3:1.2.3.6", "name4:localhost.localdomain")):
            hosts.get(name, host)

        expected = [
            mock.call.get("name1", "name1"),
            mock.call.get("name2", "name2.localdomain"),
            mock.call.get("name3", "1.2.3.6"),
            mock.call.get("name4", "localhost.localdomain"),
        ]
        result = hosts.mock_calls
        assert result == expected
Example #3
0
    def make_mock_service(self, project_quota, region_quota):
        mock_project_method = Mock()
        mock_project_method.execute = Mock(return_value={"quotas": project_quota})
        mock_projects = Mock()
        mock_projects.get = Mock(return_value=mock_project_method)

        mock_region_method = Mock()
        mock_region_method.execute = Mock(return_value={"quotas": region_quota})
        mock_regions = Mock()
        mock_regions.get = Mock(return_value=mock_region_method)

        mock_service = Mock()
        mock_service.projects = Mock(return_value=mock_projects)
        mock_service.regions = Mock(return_value=mock_regions)
        return mock_service
Example #4
0
    def logged_in(self, login="fred", travis_user=True):
        """ A context manager to do stuff, while logged in as fred. """

        response = Response()
        response._content = json.dumps(dict(id=12345, login=login, name="Fred"))
        data = Mock()
        data.get = Mock(return_value=response)
        data.access_token = GH_TOKEN

        true = Mock(return_value=True)

        if travis_user:
            travis_patch = patch("travis_utils.is_travis_user", true)
            travis_patch.start()

        with patch("statiki.github", Mock(spec=OAuth2Service)) as gh:
            gh.get_auth_session = Mock(return_value=data)

            try:
                yield self.app.get('/authorized?code="bazooka"')

            finally:
                if travis_user:
                    travis_patch.stop()

                self.app.get("/logout")
def subject_mock(id, projectID):
    s = MagicMock(name="subject", spec=pyxnat.core.resources.Subject)

    xnat = _set_mock_intf(s)
    s.id = Mock(return_value=id)
    s.datatype = Mock(return_value="xnat:subjectData")
    s._uri = "/subjects/" + id
    attrs = {"xnat:subjectData/project": projectID}
    _set_mock_attrs(attrs, s)

    # Resources

    _add_mock_resource_files(xnat, s)

    # Sessions
    exp1 = session_mock(baseURI=s._uri, xnat=xnat)

    sessions = {"1": exp1}

    get = Mock()
    get.get = Mock(side_effect=return_collection(["1"]))
    s.experiments = Mock(return_value=get)
    s.experiment = Mock(side_effect=lambda x: sessions.get(x))

    return s
Example #6
0
    def test_get_action_schema(self):
        body = {"do_stuff": {}}
        action_schema = Mock()
        action_schema.get = Mock()

        self.controller.get_action_schema(body, action_schema)
        action_schema.get.assert_called_with("do_stuff", {})
Example #7
0
def test_unpack_http_url_bad_cache_checksum(mock_unpack_file):
    """
    If cached download has bad checksum, re-download.
    """
    base_url = "http://www.example.com/somepackage.tgz"
    contents = b("downloaded")
    download_hash = hashlib.new("sha1", contents)
    link = Link(base_url + "#sha1=" + download_hash.hexdigest())

    session = Mock()
    session.get = Mock()
    response = session.get.return_value = MockResponse(contents)
    response.headers = {"content-type": "application/x-tar"}
    response.url = base_url

    cache_dir = mkdtemp()
    try:
        cache_file = os.path.join(cache_dir, urllib.quote(base_url, ""))
        cache_ct_file = cache_file + ".content-type"
        _write_file(cache_file, "some contents")
        _write_file(cache_ct_file, "application/x-tar")

        unpack_http_url(link, "location", download_cache=cache_dir, session=session)

        # despite existence of cached file with bad hash, downloaded again
        session.get.assert_called_once_with("http://www.example.com/somepackage.tgz", stream=True)
        # cached file is replaced with newly downloaded file
        with open(cache_file) as fh:
            assert fh.read() == "downloaded"

    finally:
        rmtree(cache_dir)
Example #8
0
    def test_stream_inversion_timestamps(self):
        """
    Test that if stream is inverted, timestamp of last action is the
    timestamp of the last action in the previous funnel step.
    """
        from analysis import IdentityDict
        from analysis import _stream_earliest_action

        client = Mock()
        client.get = Mock(side_effect=[self.get_stream5()])

        start = datetime.datetime(2014, 3, 20)
        end = datetime.datetime(2014, 3, 21)
        step = FunnelStep("stream5", invert=True)
        last_user_action = {"0": datetime_to_kronos_time(start), "1": datetime_to_kronos_time(start)}
        step_output = _stream_earliest_action(
            client,
            step,
            start,
            end,
            timedelta_to_kronos_time(datetime.timedelta(minutes=5)),
            last_user_action,
            {"userId": IdentityDict()},
        )
        user_action = step_output["user_action"]
        self.assertEqual(len(user_action), 1)
        self.assertEqual(user_action["1"], datetime_to_kronos_time(start))
Example #9
0
def test_crawl():
    html = """<html>
        <head>
            <title>Python is fun!</title>
        </head>
        <body>
            <div>Python is similar to Ruby, but different.</div>
        </body>
    </html>"""

    response_mock = Mock(url="http://expanded_url.com")
    response_mock.read = Mock(return_value=html)
    urllib2.urlopen = Mock(return_value=response_mock)
    url = "http://a.com"

    input_queue = Mock()
    input_queue.get = Mock(return_value=url)
    output_queue = Queue()

    crawler = Crawler()

    crawler.crawl(input_queue, output_queue)

    expected_result = {
        "CONTENT": html,
        "EXPANDED_URL": "http://expanded_url.com",
        "STATUS": "OK",
        "URL": "http://a.com",
    }

    eq_(expected_result, output_queue.get())
Example #10
0
def mock_sublime_settings(dictionary):
    def setter(key, value):
        dictionary[key] = value

    settings = Mock()
    settings.get = lambda key, default_value=None: default_value if not key in dictionary else dictionary[key]
    settings.set = setter
    return settings
    def _mock_settings_facade(self):
        """This method mocks settings facade."""

        settings_facade = Mock()
        settings_facade.get = Mock(return_value=self._DOC_BASE)
        settings_facade_cls = Mock(return_value=settings_facade)

        return settings_facade_cls
def test_parallel_computing(data_sources, thread, Queue):
    data_sources.return_value = ["1", "2"]
    m = Mock(name="Queue")
    type(m).maxsize = PropertyMock(return_value=2)
    m.get = Mock(return_value={"A": 1, "B": 1})
    Queue.return_value = m
    eq_(dict(parallel_computing.parallel_computing()), {"A": 2, "B": 2})
    eq_(m.get.call_count, 2)
Example #13
0
 def mc_factory(self, was_404):
     """
     churn out mocked caches with a preset .get(). Also a rapper?
     """
     mc = Mock()
     ret = was_404
     mc.get = Mock(return_value=ret)
     mc.set = Mock()
     return mc
Example #14
0
 def test_plain(self):
     mock = Mock()
     mock._headers = {HTTP_CONTENT_TYPE: "text/plain"}
     mock.content = "sdfsdf"
     mock.get = mock._headers.get
     factory = ResponseModelFactory(mock)
     body, content = factory.body()
     self.assertFalse(body)
     self.assertEqual(content, mock.content)
 def test_send_to_client_called(self):
     request = Mock()
     dummy_queue = Mock()
     dummy_queue.get = Mock(side_effect=[request, Spawnable.STOP])
     self.process.create_queue = Mock(return_value=dummy_queue)
     server = ServerComms(self.process)
     server.send_to_client = Mock()
     server.send_loop()
     server.send_to_client.assert_called_once_with(request)
Example #16
0
 def test_plain(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "text/plain"}
     mock_request.body = "sdfsdf"
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertFalse(body)
     self.assertEqual(raw_body, mock_request.body)
 def test_max_response(self):
     SilkyConfig().SILKY_MAX_RESPONSE_BODY_SIZE = 10  # 10kb
     mock_response = Mock()
     headers = {"CONTENT_TYPE": "text/plain"}
     mock_response.get = headers.get
     mock_response._headers = headers
     mock_response.content = "a".encode("ascii") * 1024 * 100  # 100kb
     mock_response.status_code = 200
     response_model = ResponseModelFactory(mock_response).construct_response_model()
     self.assertFalse(response_model.raw_body)
Example #18
0
 def test_utf_json_not_encoded(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "application/json; charset=UTF-8"}
     d = {"x": u"语"}
     mock_request.body = json.dumps(d)
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertDictEqual(json.loads(body), d)
     self.assertEqual(raw_body, mock_request.body)
Example #19
0
    def test_funnel(self):
        client = Mock()
        client.get = Mock(side_effect=[self.get_stream1(), self.get_stream2()])

        start = datetime.datetime(2014, 3, 20)
        end = datetime.datetime(2014, 3, 21)
        step1 = FunnelStep("stream1")
        step2 = FunnelStep("stream2")
        funnel_output = funnel_analyze(client, [step1, step2], start, end, end, {}, None)
        self.assertEqual(funnel_output.stream_sizes(), [20, 7])
Example #20
0
 def test_utf_json_not_encoded(self):
     mock = Mock()
     mock._headers = {HTTP_CONTENT_TYPE: "application/json; charset=UTF-8"}
     d = {"x": u"语"}
     mock.content = json.dumps(d)
     mock.get = mock._headers.get
     factory = ResponseModelFactory(mock)
     body, content = factory.body()
     self.assertDictEqual(json.loads(body), d)
     self.assertEqual(content, mock.content)
Example #21
0
    def test_stream_inversion_invert_and_output_fields_raises_assertion_error(self):  # noqa
        client = Mock()
        client.get = Mock(side_effect=[self.get_stream1(), self.get_stream5()])

        start = datetime.datetime(2014, 3, 20)
        end = datetime.datetime(2014, 3, 21)
        step1 = FunnelStep("stream1", output_fields=["type"])
        step2 = FunnelStep("stream5", invert=True, output_fields=["type"])
        with self.assertRaises(AssertionError):
            funnel_analyze(client, [step1, step2], start, end, end, {}, None)
Example #22
0
 def test_invalid_encoding_json(self):
     mock = Mock()
     mock._headers = {HTTP_CONTENT_TYPE: "application/json; charset=asdas-8"}
     d = {"x": u"语"}
     mock.content = json.dumps(d).encode("UTF-8")
     mock.get = mock._headers.get
     factory = ResponseModelFactory(mock)
     body, content = factory.body()
     self.assertDictEqual(json.loads(body, encoding="UTF-8"), d)
     self.assertEqual(mock.content.decode("UTF-8"), content)
Example #23
0
 def test_invalid_encoding_json(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "application/json; charset=asdas-8"}
     d = {"x": u"语"}
     mock_request.body = json.dumps(d).encode("UTF-8")
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertDictEqual(json.loads(body, encoding="UTF-8"), d)
     self.assertEqual(raw_body, raw_body)
 def leaf_module_runtime(self):
     runtime = Mock()
     runtime.render_template = lambda *args, **kwargs: u"{!r}, {!r}".format(args, kwargs)
     runtime.anonymous_student_id = "dummy_anonymous_student_id"
     runtime.open_ended_grading_interface = {}
     runtime.seed = 5
     runtime.get = lambda x: getattr(runtime, x)
     runtime.ajax_url = "dummy_ajax_url"
     runtime.xblock_model_data = lambda d: d._model_data
     return runtime
 def leaf_module_runtime(self):
     runtime = Mock()
     runtime.render_template = lambda *args, **kwargs: unicode((args, kwargs))
     runtime.anonymous_student_id = "anonymous_student_id"
     runtime.open_ended_grading_interface = {}
     runtime.seed = 5
     runtime.get = lambda x: getattr(runtime, x)
     runtime.position = 2
     runtime.ajax_url = "ajax_url"
     runtime.xblock_model_data = lambda d: d._model_data
     return runtime
    def test__list(self):
        self.instances.api.client.get = Mock(return_value=("resp", None))
        self.assertRaises(Exception, self.instances._list, "url", None)

        body = Mock()
        body.get = Mock(return_value=[{"href": "http://test.net/test_file", "rel": "next"}])
        body.__getitem__ = Mock(return_value="instance1")
        # self.instances.resource_class = Mock(return_value="instance-1")
        self.instances.api.client.get = Mock(return_value=("resp", body))
        _expected = [{"href": "http://test.net/test_file", "rel": "next"}]
        self.assertEqual(_expected, self.instances._list("url", None).links)
Example #27
0
 def test_utf_json_encoded_no_charset(self):
     """default to UTF-8"""
     mock = Mock()
     mock._headers = {HTTP_CONTENT_TYPE: "application/json"}
     d = {"x": u"语"}
     mock.content = json.dumps(d).encode("UTF-8")
     mock.get = mock._headers.get
     factory = ResponseModelFactory(mock)
     body, content = factory.body()
     self.assertDictEqual(json.loads(body), d)
     self.assertEqual(content, mock.content.decode("UTF-8"))
Example #28
0
 def test_utf_json_encoded_no_charset(self):
     """default to UTF-8"""
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "application/json"}
     d = {"x": u"语"}
     mock_request.body = json.dumps(d).encode("UTF-8")
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertDictEqual(json.loads(body), d)
     self.assertEqual(raw_body, mock_request.body.decode("UTF-8"))
 def setup(self):
     snmp = Mock()
     snmp.walk = Mock(return_value={"1": 10, "2": 20})
     snmp.get = Mock(return_value=123)
     self.time = time.time()
     main = Main()
     main.load_resolvers()
     self.mockdevice = Mock()
     self.mockdevice.hostname = "foo"
     self.mockdevice.snmp = snmp
     self.mockdevice.resolvers = main.resolvers
    def test_lookup_url_with_existing_instance(self):
        def return_instance(pk):
            return self.tracked_db_model

        class_objects = Mock(name="MockModelManager")
        class_objects.get = return_instance
        self.tracked_model.__class__.objects = class_objects

        url_tracker.track_url_changes_for_model(Mock)
        url_tracker.lookup_previous_url(self.tracked_model)

        self.assertEquals(self.tracked_model._old_url, u"/the/old/one/")