Example #1
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
 def test_convert(self, connect, popen, pipe, exists, copy):
     sqlite = self.path + "/files/test_thematic_shp_thematic.sqlite"
     shapefile = self.path + "/files/shp"
     cmd = "ogr2ogr -f 'ESRI Shapefile' {0} {1} -lco ENCODING=UTF-8".format(shapefile, sqlite)
     proc = Mock()
     exists.return_value = True
     conn = Mock()
     conn.enable_load_extention = Mock()
     connect.return_value = conn
     cur = Mock()
     conn.cursor = cur
     cur.execute = Mock()
     popen.return_value = proc
     proc.communicate.return_value = (Mock(), Mock())
     proc.wait.return_value = 0
     # set zipped to False for testing
     tags = self.job.categorised_tags
     t2s = ThematicSQliteToShp(
         sqlite=sqlite, shapefile=shapefile, tags=tags, job_name="test_thematic_shp", zipped=False, debug=True
     )
     exists.assert_called_twice()
     copy.assert_called_once()
     out = t2s.convert()
     popen.assert_called_once_with(cmd, shell=True, executable="/bin/bash", stdout=pipe, stderr=pipe)
     self.assertEquals(out, shapefile)
Example #3
0
    def test_stale_total(self, mock_wsdl_client, mock_redis):
        mock_calls = Mock()
        mock_calls.getAllActiveAlertDefinitions.return_value = 0, [AlertDefinition(1, "team1", "team2", 1, "")]
        mock_calls.getAllActiveCheckDefinitions.return_value = 0, [CheckDefinition(1, 60)]
        mock_service = PropertyMock(return_value=mock_calls)
        service_mock = Mock()
        type(service_mock).service = mock_service
        mock_wsdl_client.return_value = service_mock

        mock_client = Mock()
        mock_pipeline = Mock()
        mock_pipeline.execute = make_pipeline_execute_mock([[["e1"], ["e2", "e3"], ["e4"], ["e5"]]])
        mock_client.keys.return_value = [
            "zmon:alerts:1:entities",
            "zmon:alerts:2:entities",
            "zmon:alerts:3:entities",
            "zmon:alerts:5:entities",
        ]
        mock_client.pipeline.return_value = mock_pipeline
        mock_redis.StrictRedis.return_value = mock_client

        z = zmon.ZmonWrapper("wsdl_url", "redis_host", 6379)
        entities_count = z.check_entities_total()

        self.assertEquals(entities_count, 5)
Example #4
0
 def test_no_logged_user(self, cookie_facade):
     cmd_mock = Mock()
     cmd_mock.execute = Mock(return_value=cmd_mock)
     cmd_mock.result = None
     cookie_facade.retrive_cookie_data = Mock(return_value=cmd_mock)
     result = facade.logged_user(None).execute().result
     self.assertIsNone(result)
Example #5
0
def _build_mock():
    fetch_mock = Mock()
    fetch_mock.execute = Mock(return_value=fetch_mock)
    fetch_mock.result.content = _SUCCESS_PAGSEGURO_XML.encode("ISO-8859-1")
    fetch_mock.result.status_code = 200
    fetch_mock.errors = {}
    fetch_mock.commit = Mock(return_value=[])
    return fetch_mock
 def setup_base_mock(self, fetch_command_cls):
     app = _setup_app_data()
     fetch_cmd_obj = Mock()
     fetch_cmd_obj.errors = {}
     fetch_cmd_obj.execute = Mock(return_value=fetch_cmd_obj)
     fetch_cmd_obj.result.content = json.dumps({"id": "654321", "email": "foo@bar.com"})
     fetch_command_cls.return_value = fetch_cmd_obj
     return app, fetch_cmd_obj, Mock()
Example #7
0
def make_fake_conn(receive_returns=None):
    receive_returns = receive_returns or (["{}"], "", 0)
    conn = Mock()
    conn.return_value = conn
    conn.execute = conn
    conn.receive = Mock(return_value=receive_returns)
    conn.result = Mock(return_value=conn)
    return conn
Example #8
0
 def test_logged_user(self, cookie_facade):
     user = mommy.save_one(MainUser)
     cmd_mock = Mock()
     cmd_mock.execute = Mock(return_value=cmd_mock)
     cmd_mock.result = {"id": user.key.id()}
     cookie_facade.retrive_cookie_data = Mock(return_value=cmd_mock)
     result = facade.logged_user(None).execute().result
     self.assertEqual(user, result)
    def assertions_test(self):
        # assert_exception_test
        mock_session = Mock(**{"execute.side_effect": AlreadyExists("Dummy exception message.")})
        assert_exception(mock_session, "DUMMY QUERY", expected=AlreadyExists)

        # assert_unavailable_test
        mock_session = Mock(**{"execute.side_effect": Unavailable("Dummy Unavailabile message.")})
        assert_unavailable(mock_session.execute)

        # assert_invalid_test
        mock_session = Mock(**{"execute.side_effect": InvalidRequest("Dummy InvalidRequest message.")})
        assert_invalid(mock_session, "DUMMY QUERY")

        # assert_unauthorized_test
        mock_session = Mock(**{"execute.side_effect": Unauthorized("Dummy Unauthorized message.")})
        assert_unauthorized(mock_session, "DUMMY QUERY", None)

        # assert_one_test
        mock_session = Mock()
        mock_session.execute = Mock(return_value=[[1, 1]])
        assert_one(mock_session, "SELECT * FROM test", [1, 1])

        # assert_none_test
        mock_session = Mock()
        mock_session.execute = Mock(return_value=[])
        assert_none(mock_session, "SELECT * FROM test")

        # assert_all_test
        mock_session = Mock()
        mock_session.execute = Mock(return_value=[[i, i] for i in range(0, 10)])
        assert_all(mock_session, "SELECT k, v FROM test", [[i, i] for i in range(0, 10)], ignore_order=True)

        # assert_almost_equal_test
        assert_almost_equal(1, 1.1, 1.2, 1.9, error=1.0)

        # assert_row_count_test
        mock_session = Mock()
        mock_session.execute = Mock(return_value=[[1]])
        assert_row_count(mock_session, "test", 1)

        # assert_length_equal_test
        check = [1, 2, 3, 4]
        assert_length_equal(check, 4)
Example #10
0
    def create_command(self, name, execute_method=None):
        command = Mock()
        command.aliases = name
        command.matches = Mock()
        command.matches.return_value = True

        if execute_method:
            command.execute = execute_method

        return command
Example #11
0
    def test_execute_fail_with_multiple_params(self, query_string):
        engine_runner = Mock()
        engine_runner.execute = MagicMock()
        # noinspection PyTypeChecker
        execute_call = ExecuteCall(engine_runner)

        self.api.add_route(self.test_route, execute_call)

        self.simulate_request(self.test_route, query_string=query_string, method="POST")
        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
        engine_runner.execute.assert_not_called()
Example #12
0
    def test_execute_no_results(self):
        m_execute = Mock()
        m_cursor = Mock()
        m_cursor.execute = m_execute
        conn = Mock()
        conn.cursor.return_value = m_cursor

        dbapi2_util.execute_no_results(conn, "insert into table (a, b, c) values (%s, %s, %s)", (1, 2, 3))
        self.assertEqual(conn.cursor.call_count, 1)
        self.assertEqual(m_cursor.execute.call_count, 1)
        m_cursor.execute.assert_called_once_with("insert into table (a, b, c) values (%s, %s, %s)", (1, 2, 3))
Example #13
0
    def test_single_value_sql5(self):
        m_execute = Mock()
        m_fetchall = Mock(return_value=((17, 22),))
        m_cursor = Mock()
        m_cursor.execute = m_execute
        m_cursor.fetchall = m_fetchall
        conn = Mock()
        conn.cursor.return_value = m_cursor

        dbapi2_util.single_row_sql(conn, "select 17, 22", (1, 2, 3))
        self.assertEqual(conn.cursor.call_count, 1)
        self.assertEqual(m_cursor.execute.call_count, 1)
        m_cursor.execute.assert_called_once_with("select 17, 22", (1, 2, 3))
Example #14
0
    def create_command(self, name, priority="normal", execute_method=None):
        command = Mock()
        command.aliases = name

        command.matches = Mock()
        command.matches.return_value = True

        if execute_method:
            command.execute = execute_method

        command.priority = priority

        return command
Example #15
0
    def test_execute_with_ids(self):
        engine_runner = Mock()
        engine_runner.execute = MagicMock()
        # noinspection PyTypeChecker
        execute_call = ExecuteCall(engine_runner)

        self.api.add_route(self.test_route, execute_call)

        self.simulate_request(self.test_route, query_string="ids=1,2,3", method="POST")

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)

        engine_runner.execute.assert_called_once_with([1, 2, 3])
Example #16
0
    def test_single_row_sql1(self):
        m_execute = Mock()
        m_fetchall = Mock(return_value=((17, 22),))
        m_cursor = Mock()
        m_cursor.execute = m_execute
        m_cursor.fetchall = m_fetchall
        conn = Mock()
        conn.cursor.return_value = m_cursor

        r = dbapi2_util.single_row_sql(conn, "select 17, 22")
        eq_(r, (17, 22))
        eq_(conn.cursor.call_count, 1)
        eq_(m_cursor.execute.call_count, 1)
        m_cursor.execute.assert_called_once_with("select 17, 22", None)
Example #17
0
    def test_single_value_sql1(self):
        m_execute = Mock()
        m_fetchall = Mock(return_value=((17,),))
        m_cursor = Mock()
        m_cursor.execute = m_execute
        m_cursor.fetchall = m_fetchall
        conn = Mock()
        conn.cursor.return_value = m_cursor

        r = dbapi2_util.single_value_sql(conn, "select 17")
        self.assertEqual(r, 17)
        self.assertEqual(conn.cursor.call_count, 1)
        self.assertEqual(m_cursor.execute.call_count, 1)
        m_cursor.execute.assert_called_once_with("select 17", None)
Example #18
0
    def test_single_value_sql3(self):
        m_execute = Mock()
        m_fetchall = Mock(return_value=None)
        m_cursor = Mock()
        m_cursor.execute = m_execute
        m_cursor.fetchall = m_fetchall
        conn = Mock()
        conn.cursor.return_value = m_cursor

        assert_raises(
            dbapi2_util.SQLDidNotReturnSingleValue, dbapi2_util.single_value_sql, conn, "select 17", (1, 2, 3)
        )
        eq_(conn.cursor.call_count, 1)
        eq_(m_cursor.execute.call_count, 1)
        m_cursor.execute.assert_called_once_with("select 17", (1, 2, 3))
Example #19
0
    def test_single_value_sql4(self):
        m_execute = Mock()
        m_fetchall = Mock(return_value=None)
        m_cursor = Mock()
        m_cursor.execute = m_execute
        m_cursor.fetchall = m_fetchall
        conn = Mock()
        conn.cursor.return_value = m_cursor

        self.assertRaises(
            dbapi2_util.SQLDidNotReturnSingleRow, dbapi2_util.single_row_sql, conn, "select 17, 22", (1, 2, 3)
        )
        self.assertEqual(conn.cursor.call_count, 1)
        self.assertEqual(m_cursor.execute.call_count, 1)
        m_cursor.execute.assert_called_once_with("select 17, 22", (1, 2, 3))
Example #20
0
    def test_execute_with_statuses(self):
        trackers_manager = Mock()
        trackers_manager.get_status_topics_ids = Mock(return_value=[1, 2, 3])

        engine_runner = Mock()
        engine_runner.trackers_manager = trackers_manager
        engine_runner.execute = MagicMock()
        # noinspection PyTypeChecker
        execute_call = ExecuteCall(engine_runner)

        self.api.add_route(self.test_route, execute_call)

        self.simulate_request(self.test_route, query_string="statuses=ok,error", method="POST")

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)

        engine_runner.execute.assert_called_once_with([1, 2, 3])
        trackers_manager.get_status_topics_ids.assert_called_once_with([Status.Ok, Status.Error])
Example #21
0
    def test_execute_with_empty_topics_expect_conflict(self):
        trackers_manager = Mock()
        trackers_manager.get_tracker_topics = Mock(return_value=[])

        engine_runner = Mock()
        engine_runner.trackers_manager = trackers_manager
        engine_runner.execute = MagicMock()
        # noinspection PyTypeChecker
        execute_call = ExecuteCall(engine_runner)

        self.api.add_route(self.test_route, execute_call)

        self.simulate_request(self.test_route, query_string="tracker=tracker.tv", method="POST")

        self.assertEqual(self.srmock.status, falcon.HTTP_CONFLICT)

        engine_runner.execute.assert_not_called()
        trackers_manager.get_tracker_topics.assert_called_once_with("tracker.tv")
Example #22
0
    def test_fetchiter(self):
        cursor = Mock()

        def test_iterator(cursor, use_server_cursor=False, **kwargs):
            cursor.fetchmany = Mock(return_value=[1, 2, 3])
            num_it = 0
            for row in fetchiter(cursor, **kwargs):
                if num_it == 3:
                    raise StopIteration
                self.assertIn(row, [1, 2, 3])
                num_it += 1
                if row == 3:
                    # Stop
                    if use_server_cursor:
                        cursor.fetchall = Mock(return_value=[])
                    else:
                        cursor.fetchmany = Mock(return_value=[])
            self.assertEqual(num_it, 3)

        # Standard
        test_iterator(cursor)

        # Size
        test_iterator(cursor, size=2)
        cursor.fetchmany.assert_called_with(2)

        # Batch
        cursor.fetchmany = Mock(return_value=[1, 2])
        for row in fetchiter(cursor, batch=True):
            self.assertEqual(row, [1, 2])
            # Stop
            cursor.fetchmany = Mock(return_value=[])

        # Server cursor
        cursor.execute = Mock()
        cursor.fetchall = Mock(return_value=[1, 2, 3])
        test_iterator(cursor, use_server_cursor=True, size=10, server_cursor="C")
        calls = [call("FETCH %s FROM C", (10,))] * 2
        cursor.execute.assert_has_calls(calls)
Example #23
0
    def test_execute_query2(self):
        m_execute = Mock()
        expected = []
        returns = [None]

        def foo(*args):
            r = returns.pop(0)
            return r

        m_fetchone = Mock(side_effect=foo)
        m_cursor = Mock()
        m_cursor.execute = m_execute
        m_cursor.fetchone = m_fetchone
        conn = Mock()
        conn.cursor.return_value = m_cursor

        zipped = zip(dbapi2_util.execute_query_iter(conn, "select * from somewhere"), expected)
        for x, y in zipped:
            self.assertEqual(x, y)
        self.assertEqual(conn.cursor.call_count, 1)
        self.assertEqual(m_cursor.execute.call_count, 1)
        m_cursor.execute.assert_called_once_with("select * from somewhere", None)
 def test_generate_thematic_schema(self, connect, exists, copy):
     sqlite = self.path + "/files/test.sqlite"
     shapefile = self.path + "/files/thematic_shp"
     thematic_sqlite = self.path + "/files/test_thematic_shp_thematic.sqlite"
     exists.return_value = True
     conn = Mock()
     conn.enable_load_extention = Mock()
     connect.return_value = conn
     cur = Mock()
     conn.cursor = cur
     cur.execute = Mock()
     cmd = "SELECT load_extension('libspatialite')"
     tags = self.job.categorised_tags
     t2s = ThematicSQliteToShp(
         sqlite=sqlite, shapefile=shapefile, tags=tags, job_name="test_thematic_shp", zipped=False, debug=True
     )
     exists.assert_called_twice()
     copy.assert_called_once()
     t2s.generate_thematic_schema()
     connect.assert_called_once()
     conn.load_extention.assert_called_once()
     conn.cursor.assert_called_once()
Example #25
0
    def test_execute_with_tracker(self):
        topic1 = Mock()
        topic1.id = 1

        topic2 = Mock()
        topic2.id = 2

        trackers_manager = Mock()
        trackers_manager.get_tracker_topics = Mock(return_value=[topic1, topic2])

        engine_runner = Mock()
        engine_runner.trackers_manager = trackers_manager
        engine_runner.execute = MagicMock()
        # noinspection PyTypeChecker
        execute_call = ExecuteCall(engine_runner)

        self.api.add_route(self.test_route, execute_call)

        self.simulate_request(self.test_route, query_string="tracker=tracker.tv", method="POST")

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)

        engine_runner.execute.assert_called_once_with([1, 2])
        trackers_manager.get_tracker_topics.assert_called_once_with("tracker.tv")
 def __createMockHost(self, fakeOutput):
     host = Mock()
     cli = Mock()
     host.getCLIInstance = Mock(return_value=cli)
     cli.execute = Mock(return_value=fakeOutput)
     return host
Example #27
0
    def test_stale_alerts(self, mock_wsdl_client, mock_redis):
        mock_calls = Mock()
        # 1. Active alert with active check and up-to-date results, no time period.
        # 2. Active alert with active check and outdated results because of time period.
        # 3. Active alert with active check and up-to-date results, but the check only runs daily.
        # 4. Active alert with inactive check. (STALE)
        # 5. Active alert with active check, without time period, but with outdated results. (STALE)
        # 6. Active alert with active check, without time period, but the check doesn't match any entities, so it
        # produces no results (STALE)
        # 7. Active alert with active check, without time period, check throws an exception, results are stored, but
        # 'notify' is triggered with the exception, evaluates captures and stored keys in redis.
        mock_calls.getAllActiveAlertDefinitions.return_value = (
            0,
            [
                AlertDefinition(1, "team1", "team2", 1, ""),
                AlertDefinition(2, "team1", "team2", 2, "hr{9-17}"),
                AlertDefinition(3, "team1", "team2", 3, ""),
                AlertDefinition(4, "team1", "team2", 4, ""),
                AlertDefinition(5, "team1", "team2", 5, ""),
                AlertDefinition(6, "team1", "team2", 6, ""),
                AlertDefinition(7, "team1", "team2", 7, ""),
            ],
        )
        mock_calls.getAllActiveCheckDefinitions.return_value = (
            0,
            [
                CheckDefinition(1, 60),
                CheckDefinition(2, 40),
                CheckDefinition(3, 60 * 60 * 24),
                CheckDefinition(5, 1),
                CheckDefinition(6, 120),
                CheckDefinition(7, 60),
            ],
        )
        mock_service = PropertyMock(return_value=mock_calls)
        service_mock = Mock()
        type(service_mock).service = mock_service
        mock_wsdl_client.return_value = service_mock

        mock_client = Mock()
        mock_pipeline = Mock()
        mock_pipeline.execute = make_pipeline_execute_mock(
            [
                [
                    json.dumps({"value": 1, "ts": 55, "td": 1}),
                    json.dumps({"value": 1, "ts": 1, "td": 1}),
                    json.dumps({"value": 1, "ts": 1, "td": 1}),
                    json.dumps({"value": 1, "ts": 1, "td": 1}),
                    json.dumps({"value": 1, "ts": 1, "td": 1}),
                    None,
                    json.dumps({"value": "Exception", "ts": 1, "td": 1}),
                ],
                [["e1"], ["e2", "e3"], ["e4"], ["e5"], ["e7"]],
            ]
        )
        mock_client.keys.return_value = [
            "zmon:alerts:1:entities",
            "zmon:alerts:2:entities",
            "zmon:alerts:3:entities",
            "zmon:alerts:5:entities",
            "zmon:alerts:7:entities",
        ]
        mock_client.pipeline.return_value = mock_pipeline
        mock_redis.StrictRedis.return_value = mock_client

        with patch.object(time, "time") as mock_time:
            with patch("timeperiod.datetime") as mock_datetime:
                mock_datetime.now.return_value = datetime.datetime(2014, 5, 16, 8, 30)
                mock_time.return_value = 305
                z = zmon.ZmonWrapper("wsdl_url", "redis_host", 6379)
                inactive_alerts = z.stale_active_alerts()

        self.assertEquals(len(inactive_alerts), 3)
        self.assertEquals(inactive_alerts[0]["id"], 4)
        self.assertEquals(inactive_alerts[1]["id"], 5)
        self.assertEquals(inactive_alerts[2]["id"], 6)
Example #28
0
 def select(self):
     m = Mock()
     m.execute = self.execute
     return m