Example #1
0
    def test_fetch_options(self):
        mock = Mock()
        mock.configure_mock(**{"files.return_value.list.return_value.execute.return_value": GDRIVE_LIST_RESPONSE})

        with patch("clients.drive.build", return_value=mock):
            response = self.client.get(reverse("spreadsheet_list"))
            self.assertTrue(response.status_code, 200)

            # Only 3 inputs
            self.assertTrue(
                len([m.start() for m in re.finditer('<input type="radio" name="spreadsheet_id"', response.content)]), 3
            )
            # Only 3 anchors
            self.assertTrue(
                len(
                    [
                        m.start()
                        for m in re.finditer(
                            '<a href="http://example.com/spreadsheet/00[123]" target="_blank">Link</a>',
                            response.content,
                        )
                    ]
                ),
                3,
            )

            self.assertIn("Spreadsheet 001", response.content)
            self.assertIn("Spreadsheet 002", response.content)
            self.assertIn("Spreadsheet 003", response.content)
Example #2
0
 def test_api_base(self):
     app = Mock()
     app.configure_mock(**{"record.side_effect": AttributeError})
     api = flask_restful.Api(app)
     self.assertEquals(api.urls, {})
     self.assertEquals(api.prefix, "")
     self.assertEquals(api.default_mediatype, "application/json")
    def test_layer1(self):
        """Testing method / function layer1."""
        # Initializing key variables
        expected_dict = {
            199: {
                "cdpCacheDeviceId": "byte_string_1",
                "cdpCachePlatform": "byte_string_1",
                "cdpCacheDevicePort": "byte_string_1",
            },
            299: {
                "cdpCacheDeviceId": "byte_string_2",
                "cdpCachePlatform": "byte_string_2",
                "cdpCacheDevicePort": "byte_string_2",
            },
        }

        # Set the stage for SNMPwalk
        snmpobj = Mock(spec=Query)
        mock_spec = {"swalk.return_value": self.walk_results_string}
        snmpobj.configure_mock(**mock_spec)

        # Get results
        testobj = testimport.init_query(snmpobj)
        results = testobj.layer1()

        # Basic testing of results
        for primary in results.keys():
            for secondary in results[primary].keys():
                self.assertEqual(results[primary][secondary], expected_dict[primary][secondary])
class TestQuerySetMiddleware(TestCase):
    def setUp(self):
        self.middleware = QuerySetMiddleware()
        self.request = Mock()
        self.request.session = {}

    def test_query(self):
        self.request.configure_mock(**{"GET": {"MODEL_PATH": "django.contrib.auth.models.User", "ARGS": ""}})

        john = User(username="john", email="john@doe.com")
        john.save()
        response = self.middleware.process_request(self.request)
        self.assertEqual(200, response.status_code)
        self.assertEqual("john", json.loads(response.content.decode("utf-8"))[0].get("username"))
        self.assertEqual("john@doe.com", json.loads(response.content.decode("utf-8"))[0].get("email"))

    def test_empty_query(self):
        self.request.configure_mock(
            **{"GET": {"MODEL_PATH": "django.contrib.auth.models.User", "QUERY_ARGS": '{"username": "jane"}'}}
        )

        john = User(username="john", email="john@doe.com")
        john.save()
        response = self.middleware.process_request(self.request)
        self.assertEqual(200, response.status_code)
        self.assertEqual(
            0,
            len(json.loads(response.content.decode("utf-8"))),
            'Query result should be empty when querying for username "jane"',
        )
    def test_delays_order(self):
        """A NoticeXML's effective date can be delayed by multiple NoticeXMLs.
        Last one wins"""
        delayed, delayer1, delayer2 = Mock(), Mock(), Mock()
        delayed.configure_mock(
            published=1, fr_volume="vvv", start_page=100, end_page=200, version_id="1", **{"delays.return_value": []}
        )
        delayer1.configure_mock(
            published=2,
            fr_volume="vvv",
            start_page=200,
            end_page=300,
            version_id="2",
            **{"delays.return_value": [FRDelay("vvv", 100, "zzz-date")]}
        )
        delayer2.configure_mock(
            published=3,
            fr_volume="vvv",
            start_page=300,
            end_page=400,
            version_id="3",
            **{"delays.return_value": [FRDelay("vvv", 100, "aaa-date")]}
        )

        delays = versions.delays([delayed, delayer2, delayer1])
        self.assertEqual(delays, {"1": versions.Delay("3", "aaa-date")})

        delays = versions.delays([delayed, delayer1, delayer2])
        self.assertEqual(delays, {"1": versions.Delay("3", "aaa-date")})
Example #6
0
    def test_user_update_view_post(self):
        self.client.login(username="fred", password="secret")

        bob = get_user_model().objects.get(username="bob")

        url = reverse("kanisa_manage_users_update", args=[bob.pk])

        mock_file = Mock(spec=django.core.files.File)
        mock_file.configure_mock(name="foo.bar")
        mock_file.read.return_value = "Just some data"

        resp = self.client.post(
            url,
            {"email": "bob@example.net", "first_name": "Bob", "last_name": "Builder", "image": mock_file},
            follow=True,
        )
        self.assertEqual(resp.status_code, 200)
        self.assertTrue("form" not in resp.context)

        self.assertEqual([m.message for m in resp.context["messages"]], ['Registered User "Bob" saved.'])

        bob = get_user_model().objects.get(username="bob")

        # Clean up after our file
        bob.image.delete()

        self.assertEqual(bob.email, "bob@example.net")

        self.client.logout()
Example #7
0
    def testModelHandlerPUTModelCreate(self, createModel, getMetricDisplayFieldsMock, _engineMock):
        cols = []
        for key in METRIC_DISPLAY_FIELDS:
            m = Mock()
            m.configure_mock(name=key)
            cols.append(m)

        getMetricDisplayFieldsMock.return_value = cols

        metric = Mock(**dict((col, getattr(self.metric, col)) for col in METRIC_DISPLAY_FIELDS))
        metric.keys.return_value = [col for col in METRIC_DISPLAY_FIELDS]
        metric.name = self.metric.name

        createModel.return_value = metric

        params = {
            "type": "metric",
            "region": "us-east-1",
            "namespace": "AWS/EC2",
            "datasource": "cloudwatch",
            "metric": "CPUUtilization",
            "dimensions": {"InstanceId": "i-0c149c66"},
        }
        response = self.app.put("/", json.dumps(params), headers=self.headers)
        assertions.assertResponseStatusCode(self, response, 201)
        assertions.assertResponseHeaders(self, response, "json")
        self.assertTrue(createModel.called)
Example #8
0
    def testModelHandlerPUTImportModel(
        self, repositoryMock, createDatasourceAdapterMock, getMetricDisplayFieldsMock, quotaRepositoryMock, engineMock
    ):
        cols = []
        for key in METRIC_DISPLAY_FIELDS:
            m = Mock()
            m.configure_mock(name=key)
            cols.append(m)

        getMetricDisplayFieldsMock.return_value = cols

        metric = Mock(**dict((col, getattr(self.metric, col)) for col in METRIC_DISPLAY_FIELDS))
        metric.keys.return_value = [col for col in METRIC_DISPLAY_FIELDS]
        metric.name = self.metric.name

        quotaRepositoryMock.getInstanceCount.return_value = 0
        repositoryMock.getMetric.return_value = metric

        params = {
            "type": "metric",
            "region": "us-east-1",
            "namespace": "AWS/EC2",
            "datasource": "cloudwatch",
            "metric": "CPUUtilization",
            "dimensions": {"InstanceId": "i-0c149c66"},
        }
        response = self.app.put("/", json.dumps(params), headers=self.headers)
        assertions.assertResponseStatusCode(self, response, 201)
        assertions.assertResponseHeaders(self, response, "json")
        repositoryMock.getMetric.assert_called_once_with(
            engineMock.return_value.connect.return_value.__enter__.return_value,
            createDatasourceAdapterMock.return_value.importModel.return_value,
        )
 def _generate_worksheets_mocks(self, tabs_names):
     sub_mocks = []
     for tab in tabs_names:
         mock = Mock()
         mock.configure_mock(**{"title.text": tab})
         sub_mocks.append(mock)
     return Mock(entry=sub_mocks)
Example #10
0
    def test_report_data_passing_in_http(self, config, http):
        device = "device"
        port = "port"
        options = MagicMock(in_test_mode=False)

        http = Mock()
        response = Mock()
        attrs = {"request.return_value": (response, 3)}
        http.configure_mock(**attrs)

        data = {
            Constants.DataPacket.device: device,
            Constants.DataPacket.port: port,
            Constants.DataPacket.arrival_time: datetime.datetime(2012, 1, 2, 3, 4, 5),
            Constants.DataPacket.current_value: 10,
        }
        cs = COSMSend(options)
        cs.config = config_data = {
            "device": {
                "port": {
                    Constants.Cosm.datastream.tags: "tag",
                    Constants.Cosm.datastream.cosm_channel: "1",
                    Constants.Cosm.datastream.max_value: 100,
                    Constants.Cosm.datastream.min_value: 0,
                    Constants.Cosm.location.created: "created",
                    Constants.Cosm.location.disposition: "fixed",
                    Constants.Cosm.location.domain: "domain",
                    Constants.Cosm.location.exposure: "exposure",
                    Constants.Cosm.location.latitude: 30.3351807498968,
                    Constants.Cosm.location.longitude: 97.7104604244232 * -1.0,  # Eclipse save causes error
                    Constants.Cosm.location.private: "private",
                    Constants.Cosm.apikey: "apikey",
                    Constants.Cosm.auto_feed_url: "https://api.cosm.com/v2/feeds/64451.json",
                    Constants.Cosm.creator: "https://cosm.com/users/gary_pickens",
                    Constants.Cosm.created: "created",
                    Constants.Cosm.email: "gary_pickens@yahoo.com",
                    Constants.Cosm.feed: "https://api.cosm.com/v2/feeds/64451.json",
                    Constants.Cosm.id: 64451,
                    Constants.Cosm.private: "false",
                    Constants.Cosm.status: "frozen",
                    Constants.Cosm.tags: ["Door", "Temperature"],
                    Constants.Cosm.title: "Garage",
                    Constants.Cosm.updated: "updated",
                    Constants.Cosm.url: "url",
                    Constants.Cosm.version: "1.0.0",
                    Constants.Cosm.location_str: "location",
                    Constants.Cosm.datastreams: "datastreams",
                }
            }
        }
        json = "test"
        cs.report_data(json, data, http)
        print http.request.call_args
        http.request.assert_called_once_with(
            "url",
            body="test",
            headers={"Content-Type": "application/x-www-form-urlencoded", "X-PachubeApiKey": "apikey"},
            method="PUT",
        )
 def __init__(self, worksheets, *args, **kwargs):
     super(MockWorksheets, self).__init__(*args, **kwargs)
     sub_mocks = []
     for worksheet_name, worksheet_id in worksheets:
         mock = Mock()
         mock.configure_mock(**{"title.text": worksheet_name, "get_worksheet_id.return_value": worksheet_id})
         sub_mocks.append(mock)
     self.entry = sub_mocks
Example #12
0
 def mock_cert_dir(self):
     mocked_cd = Mock()
     product_cert = Mock()
     product = Mock()
     product.configure_mock(id=69, name="Red Hat Enterprise Linux Server")
     product_cert.configure_mock(products=[product])
     mocked_cd.find_by_product.return_value = product_cert
     self.mock(checkin, "CertificateDirectory", mocked_cd)
    def test_map_relations_invalid_id(self):
        from pyramid_skosprovider.renderers import _map_relations

        p = Mock()
        config = {"get_by_id.return_value": False, "get_vocabulary_id.return_value": "TESTPROVIDER"}
        p.configure_mock(**config)
        rels = _map_relations([5], p)
        assert len(rels) == 0
Example #14
0
    def trigger(self, http_method, path, content, mock_request):
        """ Fire an HTTP event.

        Args:
            http_method : The HTTP method
            path : The HTTP path
            content : The HTTP body
            mock_request : Mocked request to pass to the event so it can get
                           content.
        Returns:
            A tuple of (code, response)
        Raises:
            KeyError If no event is found which will handle the path.
        """
        path = self.prefix + path

        # annoyingly we return a twisted http request which has chained calls
        # to get at the http content, hence mock it here.
        mock_content = Mock()
        config = {"read.return_value": content}
        mock_content.configure_mock(**config)
        mock_request.content = mock_content

        mock_request.method = http_method
        mock_request.uri = path

        mock_request.getClientIP.return_value = "-"

        mock_request.requestHeaders.getRawHeaders.return_value = ["X-Matrix origin=test,key=,sig="]

        # return the right path if the event requires it
        mock_request.path = path

        # add in query params to the right place
        try:
            mock_request.args = urlparse.parse_qs(path.split("?")[1])
            mock_request.path = path.split("?")[0]
            path = mock_request.path
        except:
            pass

        for (method, pattern, func) in self.callbacks:
            if http_method != method:
                continue

            matcher = pattern.match(path)
            if matcher:
                try:
                    args = [urllib.unquote(u).decode("UTF-8") for u in matcher.groups()]

                    (code, response) = yield func(mock_request, *args)
                    defer.returnValue((code, response))
                except CodeMessageException as e:
                    defer.returnValue((e.code, cs_error(e.msg)))

        raise KeyError("No event can handle %s" % path)
    def __init__(self, cells, *args, **kwargs):
        super(MockCells, self).__init__(*args, **kwargs)
        sub_mocks = []

        for cell_id, cell_name in cells:
            if cell_name:
                mock = Mock()
                mock.configure_mock(**{"id.text": SPREADSHEET_URL_FORMAT % cell_id, "content.text": cell_name})
                sub_mocks.append(mock)
        self.entry = sub_mocks
Example #16
0
 def test_edit_contact_record_last_action_time(self):
     """
         Verify last action time is updated when contact record form is edited
     """
     request = Mock()
     request.configure_mock(user=self.contact_user, impersonator=None)
     original_time = self.contact_record.last_action_time
     self.assertEqual(original_time, self.form.instance.last_action_time)
     saved_form_instance = self.form.save(request=request, partner=self.partner)
     self.assertNotEqual(original_time, saved_form_instance.last_action_time)
Example #17
0
    def test_send_raises_connection_error(self):
        mock_transport = Mock(name="transport")
        mockcfg = {"getresponse.return_value.read.side_effect": ValueError}
        mock_transport.configure_mock(**mockcfg)

        instance = pyeapi.eapilib.EapiConnection()
        instance.transport = mock_transport

        with self.assertRaises(pyeapi.eapilib.ConnectionError):
            instance.send("test")
 def test_request_ignores_responses_that_do_not_require_2fa(self, request_mock):
     """Test that request does not try to handle 2fa when it should not"""
     response = Mock()
     response.configure_mock(status_code=200, headers={})
     request_mock.return_value = response
     s = self.build_session()
     s.two_factor_auth_callback(lambda: "fake")
     r = s.get("http://example.com")
     assert r is response
     request_mock.assert_called_once_with("GET", "http://example.com", allow_redirects=True)
 def test_creates_history_while_handling_2fa(self, request_mock):
     """Test that the overridden request method will create history"""
     response = Mock()
     response.configure_mock(status_code=401, headers={"X-GitHub-OTP": "required;2fa"}, history=[])
     request_mock.return_value = response
     s = self.build_session()
     s.two_factor_auth_callback(lambda: "fake")
     r = s.get("http://example.com")
     assert len(r.history) != 0
     assert request_mock.call_count == 2
Example #20
0
    def test_spreadsheet_fetching(self):
        mock = Mock()
        mock.configure_mock(**{"files.return_value.list.return_value.execute.return_value": GDRIVE_LIST_RESPONSE})

        with patch("clients.drive.build", return_value=mock):
            client = SimpleDriveClient(MockedCredentials())
            spreadsheets = client.get_spreadsheet_list()
            self.assertTrue(len(spreadsheets), 3)
            self.assertEqual(
                [item["title"] for item in spreadsheets], ["Spreadsheet 001", "Spreadsheet 002", "Spreadsheet 003"]
            )
Example #21
0
 def test_add_contact_record_last_action_time(self):
     """
         Verify last action time is created when contact record form is saved
     """
     request = Mock()
     request.configure_mock(user=self.contact_user, impersonator=None)
     new_form = ContactRecordForm(data=self.data, partner=self.partner)
     self.assertTrue(new_form.is_valid())
     self.assertIsNone(new_form.fields.get("last_action_time"))
     saved_form_instance = new_form.save(request=request, partner=self.partner)
     self.assertIsNotNone(saved_form_instance.last_action_time)
    def test_projects(self, sm):
        session = Mock()
        mock_projects = [("Project1")]
        config = {"return_value.query.return_value.distinct.return_value.order_by.return_value": mock_projects}
        session.configure_mock(**config)
        sm.return_value = session
        views = Views(self.request)

        projects = views.projects()

        self.assertEqual(projects, [{"id": "Project1", "text": "Project1"}])
    def test_species(self, sm):
        session = Mock()
        mock_species = ["Lesser Black-backed Gull"]
        config = {"return_value.query.return_value.distinct.return_value.order_by.return_value": mock_species}
        session.configure_mock(**config)
        sm.return_value = session
        views = Views(self.request)

        species = views.species()

        self.assertEqual(species, [{"id": "Lesser Black-backed Gull", "text": "Lesser Black-backed Gull"}])
Example #24
0
 def _create_mock_request(**overrides):
     defaults = dict(
         fullurl="https://www.reddit.com/",
         user_agent="msnbot/2.0b (+http://search.msn.com/msnbot.htm)",
         method="GET",
         domain="reddit.local",
         referrer=None,
     )
     mock_request = Mock(spec=Request)
     mock_request.configure_mock(**dict(defaults, **overrides))
     return mock_request
    def test_upper_level(self, logger_obj, handler_cls):
        handler = Mock()
        handler.configure_mock(level=logging.INFO)
        handler_cls.return_value = handler

        with log_helpers.QuietLogger(logging.WARNING):
            log_helpers.logger.warning("Test")

        handler.assert_has_calls((call.setLevel(logging.WARNING + 1), call.setLevel(logging.INFO)))

        logger_obj.assert_has_calls((call.warning("Test"),))
    def test_rtl_support(self, xblock, text_direction):
        bidi = text_direction == "rtl"

        # Configure "i18n_service" of xblock runtime with dummy response
        i18nService = Mock()
        attrs = {"get_language_bidi.return_value": bidi}
        i18nService.configure_mock(**attrs)
        xblock.runtime._services["i18n"] = i18nService

        css_path = xblock.student_view_css_path()
        self.assertEqual(css_path, "static/reverification-{dir}.min.css".format(dir=text_direction))
Example #27
0
    def test_some_version(self, urlopen_mock):
        mock_response = Mock()
        if six.PY2:
            config = {"info.return_value.getheader.return_value": "Version42"}

        if six.PY3:
            config = {"getheader.return_value": "Version42"}

        mock_response.configure_mock(**config)
        urlopen_mock.side_effect = [mock_response]
        self.assertEqual(self.j.get_version(), "Version42")
        self._check_requests(urlopen_mock.call_args_list)
Example #28
0
 def test_deploy_fail_process(self, popen_func):
     popen_mock = Mock()
     attrs = {"wait.return_value": 1}
     popen_mock.configure_mock(**attrs)
     popen_func.return_value = popen_mock
     try:
         path = os.getcwd()
         test_deploy = LambdaDeploy(path, "s3://pb-gravity", None)
         test_deploy.deploy()
     except Exception as e:
         popen_mock.wait.assert_any_call()
         self.assertTrue(popen_mock.wait.call_count == 1, "Popen.wait was called more than once before failing!")
Example #29
0
class TestDNS(unittest.TestCase):
    def setUp(self):
        self.bot = Mock()
        self.server = Mock()
        self.event = Mock()
        self.dns_obj = dns.dns(self.bot)

    def test_single_token(self):
        attrs = {"target": "channel", "tokens": ["!dns"]}
        self.event.configure_mock(**attrs)
        self.dns_obj.dns(self.server, self.event, self.bot)

        self.server.privmsg.assert_called_with("channel", "Nothing to look up, zoob!")

    @patch.object(dns, "socket")
    def test_good_ip(self, mock_socket):
        attrs = {"target": "channel", "tokens": ["!dns", "10.0.0.10"]}
        self.event.configure_mock(**attrs)
        mock_socket.gethostbyaddr.return_value = ("scrappy.example", [], [])
        self.dns_obj.dns(self.server, self.event, self.bot)

        self.server.privmsg.assert_called_with("channel", "10.0.0.10 -> scrappy.example")

    @patch.object(dns, "socket")
    def test_bad_ip(self, mock_socket):
        attrs = {"gaierror": Exception}
        mock_socket.configure_mock(**attrs)
        mock_socket.gethostbyaddr.side_effect = mock_socket.gaierror
        attrs = {"target": "channel", "tokens": ["!dns", "10.0.0.10"]}
        self.event.configure_mock(**attrs)
        self.dns_obj.dns(self.server, self.event, self.bot)

        self.server.privmsg.assert_called_with("channel", "No result for '10.0.0.10'")

    @patch.object(dns, "socket")
    def test_good_domain(self, mock_socket):
        attrs = {"target": "channel", "tokens": ["!dns", "scrappy.example"]}
        self.event.configure_mock(**attrs)
        mock_socket.gethostbyname.return_value = "10.0.0.10"
        self.dns_obj.dns(self.server, self.event, self.bot)

        self.server.privmsg.assert_called_with("channel", "scrappy.example -> 10.0.0.10")

    @patch.object(dns, "socket")
    def test_bad_domain(self, mock_socket):
        attrs = {"gaierror": Exception}
        mock_socket.configure_mock(**attrs)
        mock_socket.gethostbyname.side_effect = mock_socket.gaierror
        attrs = {"target": "channel", "tokens": ["!dns", "scrappy.example"]}
        self.event.configure_mock(**attrs)
        self.dns_obj.dns(self.server, self.event, self.bot)

        self.server.privmsg.assert_called_with("channel", "No result for 'scrappy.example'")
Example #30
0
    def _call_handle_done(self, status, response_body, action, from_page):
        mock_session = Mock()
        mock_msg = Mock()
        cfgstr = "response_body.flatten.return_value" ".get_data.return_value.decode.return_value"
        cfg = {cfgstr: response_body}
        mock_msg.configure_mock(**cfg)
        mock_status_code = PropertyMock(return_value=status)
        type(mock_msg).status_code = mock_status_code

        info = {"action": action, "from_page": from_page}
        self.page._handle_soup_message_done(mock_session, mock_msg, info)
        self.assertEqual(self.page.notebook_main.get_current_page(), from_page)