Example #1
0
    def test_report_customers_by_products(self):
        """ Unit test to customers grouped by product report.
        """
        # Mock sale model and products models
        salesList = []
        keys = [2, 1, 3, 2, 1]
        for x in keys:
            sale = Mock(spec_set=saleModel.SaleModel())
            sale.product = Mock(spec_set=productModel.ProductModel())
            sale.product.key = Mock(spec_set=ndb.Key("ProductModel", x))
            sale.product.key.id = Mock(return_value=x)
            sale.product.key.get = Mock(return_value=sale.product)
            salesList.append(sale)

        # Mock customers models
        keys = [{"id": "1", "name": "Test1"}, {"id": "2", "name": "Test2"}]
        for sale in salesList:
            sale.customer = Mock(spec_set=customerModel.CustomerModel())
            customer = keys[randint(0, 1)]
            sale.customer.key = Mock(spec_set=ndb.Key("CustomerModel", customer["id"]))
            sale.customer.key.id = Mock(return_value=customer["id"])
            sale.customer.key.get = Mock(return_value=customer)
            sale.customer.name = PropertyMock(return_value=customer["name"])

        # Mock fetch method
        mockSale = Mock(spec_set=saleModel.SaleModel())
        mockSale.query = Mock(spec=mockSale.query)
        mockSale.query().fetch = MagicMock(return_value=salesList)

        # Set get_sales_query to return query mocked
        saleModel.get_sales_query = MagicMock(return_value=mockSale.query())

        # Call report_customers_by_product method
        result = saleModel.report_customers_by_products()

        # Must have lenght == 3
        self.assertEqual(len(result), 3)

        # The result must be:
        #   Product 1 => 2 Customers
        #   Product 2 => 2 Customers
        #   Product 3 => 1 Customer
        self.assertEqual(len(result[0]["customers"]), 2)
        self.assertEqual(len(result[1]["customers"]), 2)
        self.assertEqual(len(result[2]["customers"]), 1)

        # And the products must be ordered
        self.assertEqual(result[0]["product"].key.id(), 1)
        self.assertEqual(result[1]["product"].key.id(), 2)
        self.assertEqual(result[2]["product"].key.id(), 3)
Example #2
0
    def test_report_products_by_customers(self):
        """ Unit test to products grouped by customers report.
        """
        # Mock sale model and products models
        salesList = []
        keys = [2, 1, 3, 2, 1]
        for x in keys:
            sale = Mock(spec_set=saleModel.SaleModel())
            sale.customer = Mock(spec_set=customerModel.CustomerModel())
            sale.customer.key = Mock(spec_set=ndb.Key("CustomerModel", x))
            sale.customer.key.id = Mock(return_value=x)
            sale.customer.key.get = Mock(return_value=sale.customer)
            salesList.append(sale)

        # Mock products models
        keys = [2, 3, 1]
        for sale in salesList:
            sale.product = Mock(spec_set=productModel.ProductModel())
            key_id = keys[randint(0, 2)]
            sale.product.key = Mock(spec_set=ndb.Key("ProductModel", key_id))
            sale.product.key.id = Mock(return_value=key_id)
            sale.product.key.get = Mock(return_value=sale.product)

        # Mock fetch method
        mockSale = Mock(spec_set=saleModel.SaleModel())
        mockSale.query = Mock(spec=mockSale.query)
        mockSale.query().fetch = MagicMock(return_value=salesList)

        # Set get_sales_query to return query mocked
        saleModel.get_sales_query = MagicMock(return_value=mockSale.query())

        # Call report_customers_by_product method
        result = saleModel.report_products_by_customers()

        # Must have lenght == 3
        self.assertEqual(len(result), 3)

        # The result must be:
        #   Customer 1 => 2 Customers
        #   Customer 2 => 2 Customers
        #   Customer 3 => 1 Customer
        self.assertEqual(len(result[0]["products"]), 2)
        self.assertEqual(len(result[1]["products"]), 2)
        self.assertEqual(len(result[2]["products"]), 1)

        # And the customers must be ordered
        self.assertEqual(result[0]["customer"].key.id(), 1)
        self.assertEqual(result[1]["customer"].key.id(), 2)
        self.assertEqual(result[2]["customer"].key.id(), 3)
Example #3
0
    def test_run(self, *mocks):

        eddaclient = Mock()
        eddaclient._since = 500

        def ret_list(args):
            return [
                {"imageId": "ami-1", "instanceId": "a", "launchTime": 400, "tags": [{"key": "Name", "value": "tag1"}]},
                {
                    "imageId": "ami-2",
                    "instanceId": "b",
                    "launchTime": 600,
                    "tags": [{"key": "service_name", "value": "foo"}],
                },
                {
                    "imageId": "ami-3",
                    "instanceId": "c",
                    "launchTime": 800,
                    "tags": [{"key": "Name", "value": "tag1"}, {"key": "service_name", "value": "foo"}],
                },
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.clean = Mock(return_value=m)
        self.plugin.init(eddaclient, Mock(), {})

        # run the tested method
        self.assertEqual(self.plugin.run(), [{"id": "foo", "plugin_name": "newtag", "details": ["b, c"]}])

        m.query.assert_has_calls([call("/api/v2/view/instances;_expand")])
Example #4
0
    def test_old_query_params_except_offset_with_equals(self):
        uri = Mock()
        uri.query = "foo=spam=ham&offset=bar"
        result = []

        helpers._get_old_query_params_except_offset(result, uri)
        self.assertEqual(result, ["foo=spam%3Dham"])
Example #5
0
    def test_nonempty_status(self, *mocks):
        instance_enricher = InstanceEnricher(Mock())
        eddaclient = Mock()

        def ret_list(args):
            return [
                {
                    "keyName": "keyName1",
                    "instanceId": "a",
                    "privateIpAddress": "10.1.1.1",
                    "publicIpAddress": "1.1.1.1",
                    "tags": [{"key": "Name", "value": "tag1"}, {"a": "b"}],
                    "launchTime": 6 * 3600000 + 1,
                },
                {
                    "keyName": "keyName2",
                    "instanceId": "b",
                    "privateIpAddress": "10.1.1.2",
                    "publicIpAddress": "2.1.1.1",
                    "tags": [{"key": "service_name", "value": "foo"}],
                    "launchTime": 7 * 3600000 + 1,
                },
                {
                    "keyName": "keyName3",
                    "instanceId": "c",
                    "privateIpAddress": "10.1.1.3",
                    "publicIpAddress": "3.1.1.1",
                    "launchTime": 8 * 3600000 + 1,
                },
                {
                    "keyName": "keyName4",
                    "instanceId": "d",
                    "privateIpAddress": "10.1.1.4",
                    "publicIpAddress": "4.1.1.1",
                    "launchTime": 9 * 3600000 + 1,
                },
                {"instanceId": "e", "privateIpAddress": "x", "publicIpAddress": "x", "launchTime": 10 * 3600000 + 1},
                {"instanceId": "f", "privateIpAddress": "x", "publicIpAddress": "x", "launchTime": 11 * 3600000 + 1},
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.soft_clean = Mock(return_value=m)
        eddaclient._since = 10 * 3600000
        eddaclient._until = 11 * 3600000

        def chef_list(*args, **kwargs):
            return [
                {"name": "host0", "automatic": {"cloud": {"public_ipv4": "5.1.1.1"}}},
                {"name": "host1", "automatic": {"cloud": {"public_ipv4": "6.1.1.1"}}},
                {"name": "host2", "automatic": {"cloud": {"public_ipv4": "7.1.1.1"}}},
            ]

        with patch("plugins.chef.Search", side_effect=chef_list) as MockClass:
            self.plugin.init(eddaclient, self.config, {"first_seen": {"f": 8}}, instance_enricher)

            alerts = list(self.plugin.do_run())
            # there is one problematic node (2.1.1.1)
            self.assertEqual(1, len(alerts))
            self.assertTrue(any(a["details"][0]["publicIpAddress"] == "2.1.1.1" for a in alerts))
Example #6
0
    def test_ignore_tags(self, *mocks):
        instance_enricher = InstanceEnricher(Mock())
        eddaclient = Mock()
        eddaclient._since = 500

        def ret_list(args):
            return [
                {"imageId": "ami-1", "instanceId": "a", "launchTime": 400, "tags": [{"key": "Name", "value": "tag1"}]},
                {
                    "imageId": "ami-2",
                    "instanceId": "b",
                    "launchTime": 600,
                    "tags": [{"key": "service_name", "value": "testapp"}],
                },
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.clean = Mock(return_value=m)
        self.plugin.init(eddaclient, Mock(), {}, instance_enricher)

        # run the tested method
        result = self.plugin.run()
        self.assertEqual(0, len(result))

        m.query.assert_has_calls([call("/api/v2/view/instances;_expand")])
Example #7
0
    def test_run(self, *mocks):
        eddaclient = Mock()
        eddaclient._since = 500

        def ret_list(args):
            return [
                {"name": "info.prezi.com", "instanceId": "a", "launchTime": 400},
                {"name": "info.prezi.com", "instanceId": "a", "launchTime": 400},
                {"name": "info.prezi.com", "instanceId": "a", "launchTime": 400},
                {"name": "info1.prezi.com", "instanceId": "b", "launchTime": 600},
                {"name": "info1.prezi.com", "instanceId": "b", "launchTime": 600},
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.clean = Mock(return_value=m)

        self.assertEqual(
            [
                {"name": "info.prezi.com", "instanceId": "a", "launchTime": 400},
                {"name": "info1.prezi.com", "instanceId": "b", "launchTime": 600},
            ],
            load_route53_entries(eddaclient),
        )
        m.query.assert_has_calls([call("/api/v2/aws/hostedRecords;_expand")])
Example #8
0
    def test_old_query_params_except_offset(self):
        uri = Mock()
        uri.query = "foo=bar&spam=ham"
        result = []

        helpers._get_old_query_params_except_offset(result, uri)
        self.assertEqual(result, ["foo=bar", "spam=ham"])
Example #9
0
def mock_sql():
    mock_sql_query = Mock(spec_set=["_execute_sql", "query", "as_sql"])
    mock_sql_query._execute_sql = Mock()
    mock_sql_query.query = NonCallableMock(spec_set=["model"])
    mock_sql_query.query.model = Mock()
    query_string = "SELECT * from table_name"
    mock_sql_query.as_sql = Mock(return_value=(query_string, ()))
    return mock_sql_query, query_string
Example #10
0
    def test_run(self, *mocks):

        eddaclient = Mock()

        def ret_list(args):
            return [
                {
                    "loadBalancerName": "test-elb",
                    "canonicalHostedZoneName": "test-hostname",
                    "instances": [{}, {}],
                    "listenerDescriptions": [
                        {
                            "listener": {
                                "SSLCertificateId": None,
                                "instancePort": 8443,
                                "instanceProtocol": "TCP",
                                "loadBalancerPort": 22,
                                "protocol": "TCP",
                            },
                            "policyNames": [],
                        }
                    ],
                },
                {
                    "loadBalancerName": "production-elb",
                    "canonicalHostedZoneName": "production-hostname",
                    "instances": [{}, {}, {}, {}, {}],
                    "listenerDescriptions": [
                        {
                            "listener": {
                                "SSLCertificateId": None,
                                "instancePort": 8443,
                                "instanceProtocol": "TCP",
                                "loadBalancerPort": 443,
                                "protocol": "TCP",
                            },
                            "policyNames": [],
                        }
                    ],
                },
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.updateonly = Mock(return_value=m)
        self.plugin.init(eddaclient, self.config, {})

        # run the tested method
        result = self.plugin.run()
        self.assertEqual(1, len(result))
        self.assertIn("id", result[0])
        self.assertIn("plugin_name", result[0])
        self.assertIn("details", result[0])

        self.assertTrue(isinstance(result[0]["details"], list))
        self.assertEqual(1, len(result[0]["details"]))

        m.query.assert_has_calls([call("/api/v2/aws/loadBalancers;_expand")])
Example #11
0
    def test_handle_invalid_chef_data(self, *mocks):
        instance_enricher = InstanceEnricher(Mock())
        eddaclient = Mock()

        def ret_list(args):
            return [
                {
                    "keyName": "keyName1",
                    "instanceId": "a",
                    "privateIpAddress": "10.1.1.1",
                    "publicIpAddress": "1.1.1.1",
                    "tags": [{"key": "Name", "value": "tag1"}, {"a": "b"}],
                    "launchTime": 1 * 3600000,
                },
                {
                    "keyName": "keyName2",
                    "instanceId": "b",
                    "privateIpAddress": "10.1.1.2",
                    "publicIpAddress": "2.1.1.1",
                    "tags": [{"key": "service_name", "value": "foo"}],
                    "launchTime": 1 * 3600000,
                },
                {
                    "keyName": "keyName3",
                    "instanceId": "c",
                    "privateIpAddress": "10.1.1.3",
                    "publicIpAddress": "3.1.1.1",
                    "launchTime": 1 * 3600000,
                },
                {
                    "keyName": "keyName4",
                    "instanceId": "d",
                    "privateIpAddress": "10.1.1.4",
                    "publicIpAddress": "4.1.1.1",
                    "launchTime": 1 * 3600000,
                },
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.soft_clean = Mock(return_value=m)
        eddaclient._since = 3 * 3600000
        eddaclient._until = 4 * 3600000 + 1

        def chef_list(*args, **kwargs):
            return [
                {"name": "host3", "automatic": {"cloud": {"foo": "1.1.1.1"}}},
                {"name": "host4", "automatic": {"foo": {"public_ipv4": "2.1.1.1"}}},
                {"foo": {"cloud": {"public_ipv4": "3.1.1.1"}}},
            ]

        with patch("plugins.chef.Search", side_effect=chef_list):
            self.plugin.init(eddaclient, self.config, {}, instance_enricher)

            alerts = list(self.plugin.do_run())

            # no valid chef data was returned
            self.assertEqual(0, len(alerts))
Example #12
0
    def test_badwords(self):
        db = Mock()
        db.query = Mock(
            return_value=[{"kill_words": "asshole other dirty words", "warn_words": "jerk kinda bad stuff"}]
        )

        self.assertEqual(censor.badwords(db, "asshole"), 2)
        self.assertEqual(censor.badwords(db, "jerk"), 1)
        self.assertEqual(censor.badwords(db, "unicorn"), 0)
Example #13
0
    def test_run(self, *mocks):

        eddaclient = Mock()
        default_users = ["bob", "alice"]
        whitelisted_users = ["whitelisteduser123123"]
        allowed_list = ["^whitelisteduser[\d]{6}$"]
        users = default_users + whitelisted_users
        diff_call_format = "/api/v2/aws/iamUsers/%s;_diff=200"

        def ret_list(args):
            return users

        def ret_user_diff(args):
            if args == diff_call_format % "alice":
                return open(APPDIR + "test_data/test_iam_diff.txt").read()
            else:
                return '"diff" without group change'

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.raw_query = Mock(side_effect=ret_user_diff)
        eddaclient.updateonly = Mock(return_value=m)

        mocked_config = {}
        mocked_config["allowed"] = allowed_list

        self.plugin.init(eddaclient, mocked_config, {})

        # run the tested method
        self.assertEqual(
            self.plugin.run(),
            [
                {
                    "id": "alice",
                    "plugin_name": "iam",
                    "details": ["Groups the user has been added to: developers, devops"],
                }
            ],
        )

        m.query.assert_has_calls([call("/api/v2/aws/iamUsers")])
        # switched to assertEqual so we can detect if the whitelisted user is indeed not checked
        self.assertEqual(
            eddaclient.raw_query.call_args_list, [call(diff_call_format % username) for username in default_users]
        )
Example #14
0
    def test_run(self, *mocks):

        eddaclient = Mock()
        eddaclient._since = 500

        def ret_list(args):
            return [
                {
                    "imageId": "ami-1",
                    "instanceId": "a",
                    "launchTime": "500",
                    "tags": [{"key": "service_name", "value": "conversion"}, {"key": "started_by", "value": "john"}],
                },
                {
                    "imageId": "ami-1",
                    "instanceId": "b",
                    "launchTime": "2000",
                    "tags": [{"key": "service_name", "value": "router"}],
                },
                {"imageId": "ami-2", "instanceId": "c", "launchTime": "400"},
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.clean = Mock(return_value=m)
        self.plugin.init(eddaclient, self.config, {"first_seen": {"ami-1": 1000, "ami-2": 400}})

        real = self.plugin.run()
        expected = [
            {
                "id": "ami-1",
                "plugin_name": "ami",
                "details": [
                    ("a", 500, [{"service_name": "conversion"}, {"started_by": "john"}]),
                    ("b", 2000, [{"service_name": "router"}]),
                ],
            }
        ]

        self.assertEqual(expected, real)

        m.query.assert_has_calls([call("/api/v2/view/instances;_expand")])
        self.assertEqual(self.plugin.status, {"first_seen": {"ami-1": 500, "ami-2": 400}})
    def test_getClient_connectionfailed(self):
        mock_storage = Mock(spec=DatabaseStorage)
        mock_storage.getClient = DatabaseStorage.getClient
        mock_storage.db = None
        mock_storage.query = Mock(return_value=None)
        mock_storage.console = Mock()
        mock_storage.console.config = Mock()
        mock_storage.console.config.get = Mock(return_value="123,myname,100")

        mock_storage.console.config.has_option = Mock(return_value=True)
        c1 = Client()
        c2 = mock_storage.getClient(mock_storage, c1)
        self.assertIs(c2, c1)
        self.assertEqual(123, c1.id)
        self.assertEqual("myname", c1.name)
        self.assertEqual(100, c1._tempLevel)

        mock_storage.console.config.has_option = Mock(return_value=False)
        self.assertRaises(KeyError, mock_storage.getClient, mock_storage, Mock())
Example #16
0
    def test_run(self, *mocks):
        instance_enricher = InstanceEnricher(Mock())

        eddaclient = Mock()
        eddaclient._since = 500

        def ret_list(args):
            return [
                {
                    "imageId": "ami-1",
                    "instanceId": "a",
                    "launchTime": "500",
                    "tags": [{"key": "service_name", "value": "conversion"}, {"key": "started_by", "value": "john"}],
                },
                {
                    "imageId": "ami-1",
                    "instanceId": "b",
                    "launchTime": "2000",
                    "tags": [{"key": "service_name", "value": "router"}],
                },
                {"imageId": "ami-2", "instanceId": "c", "launchTime": "400"},
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.soft_clean = Mock(return_value=m)
        self.plugin.init(eddaclient, self.config, {"first_seen": {"ami-1": 1000, "ami-2": 400}}, instance_enricher)

        result = self.plugin.run()

        self.assertEqual(1, len(result))
        result = result[0]
        self.assertEqual("ami-1", result["id"])
        self.assertEqual(2, len(result["details"]))
        self.assertIn("a", [d["instanceId"] for d in result["details"]])
        self.assertIn("b", [d["instanceId"] for d in result["details"]])

        m.query.assert_has_calls([call("/api/v2/view/instances;_expand")])
        self.assertEqual(self.plugin.status, {"first_seen": {"ami-1": 500, "ami-2": 400}})
Example #17
0
    def test_skipped_service(self):
        eddaclient = Mock()
        eddaclient.query = Mock(
            return_value=[
                {
                    "imageId": "ami-1",
                    "instanceId": "b",
                    "launchTime": "2000",
                    "tags": [{"key": "service_name", "value": "jenkins"}],
                }
            ]
        )
        uncleaned_eddaclient = Mock()
        uncleaned_eddaclient.clean = Mock(return_value=eddaclient)
        uncleaned_eddaclient._since = 500

        self.plugin.init(uncleaned_eddaclient, self.config, {"first_seen": {}})

        real = self.plugin.run()
        expected = []

        self.assertEqual(expected, real)
        eddaclient.query.assert_has_calls([call("/api/v2/view/instances;_expand")])
Example #18
0
    def test_run(self, *mocks):
        instance_enricher = InstanceEnricher(Mock())
        eddaclient = Mock()
        eddaclient._since = 500

        def ret_list(args):
            return [
                {"imageId": "ami-1", "instanceId": "a", "launchTime": 400, "tags": [{"key": "Name", "value": "tag1"}]},
                {
                    "imageId": "ami-2",
                    "instanceId": "b",
                    "launchTime": 600,
                    "tags": [{"key": "service_name", "value": "foo"}],
                },
                {
                    "imageId": "ami-3",
                    "instanceId": "c",
                    "launchTime": 800,
                    "tags": [{"key": "Name", "value": "tag1"}, {"key": "service_name", "value": "foo"}],
                },
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.clean = Mock(return_value=m)
        self.plugin.init(eddaclient, Mock(), {}, instance_enricher)

        # run the tested method
        result = self.plugin.run()
        self.assertEqual(1, len(result))
        result = result[0]
        self.assertEqual("foo", result["id"])
        self.assertEqual(2, len(result["details"]))
        self.assertIn("b", [d["instanceId"] for d in result["details"]])
        self.assertIn("c", [d["instanceId"] for d in result["details"]])

        m.query.assert_has_calls([call("/api/v2/view/instances;_expand")])
Example #19
0
    def test_empty_status(self, *mocks):
        instance_enricher = InstanceEnricher(Mock())
        eddaclient = Mock()

        def ret_list(args):
            return [
                {
                    "keyName": "keyName1",
                    "instanceId": "a",
                    "privateIpAddress": "10.1.1.1",
                    "publicIpAddress": "1.1.1.1",
                    "tags": [{"key": "Name", "value": "tag1"}, {"a": "b"}],
                    "launchTime": 1 * 3600000,
                },
                {
                    "keyName": "keyName2",
                    "instanceId": "b",
                    "privateIpAddress": "10.1.1.2",
                    "publicIpAddress": "2.1.1.1",
                    "tags": [{"key": "service_name", "value": "foo"}],
                    "launchTime": 1 * 3600000,
                },
                {
                    "keyName": "keyName3",
                    "instanceId": "c",
                    "privateIpAddress": "10.1.1.3",
                    "publicIpAddress": "3.1.1.1",
                    "launchTime": 1 * 3600000,
                },
                {
                    "keyName": "keyName4",
                    "instanceId": "d",
                    "privateIpAddress": "10.1.1.4",
                    "publicIpAddress": "4.1.1.1",
                    "launchTime": 1 * 3600000,
                },
                {
                    "keyName": "keyName5",
                    "instanceId": "e",
                    "privateIpAddress": "null",
                    "publicIpAddress": "null",
                    "launchTime": 1 * 3600000,
                },
                {
                    "keyName": "keyName6",
                    "instanceId": "f",
                    "privateIpAddress": None,
                    "publicIpAddress": None,
                    "launchTime": 1 * 3600000,
                },
            ]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.soft_clean = Mock(return_value=m)
        eddaclient._since = 3 * 3600000
        eddaclient._until = 4 * 3600000 + 1

        def chef_list(*args, **kwargs):
            return [
                {"name": "ec2 alive", "automatic": {"cloud": {"public_ipv4": "1.1.1.1", "provider": "ec2"}}},
                {"name": "non-ec2 but cloud host alive", "automatic": {"cloud": {"public_ipv4": "2.1.1.1"}}},
                {"name": "ec2 host dead", "automatic": {"cloud": {"public_ipv4": "255.1.1.1", "provider": "ec2"}}},
                {"name": "non-ec2 host", "automatic": {"ipaddress": "5.1.1.1"}},
            ]

        with patch("plugins.chef.Search", side_effect=chef_list) as MockClass:
            self.plugin.init(eddaclient, self.config, {}, instance_enricher)

            alerts = list(self.plugin.do_run())
            non_chef_alerts = [i for i in alerts if i["plugin_name"] == "non_chef"]
            chef_managed_alerts = [i for i in alerts if i["plugin_name"] == "chef_managed"]

            # there are two reportable instances, 3.1.1.1 and 4.1.1.1
            self.assertEqual(2, len(non_chef_alerts))
            self.assertTrue(any(a["details"][0]["publicIpAddress"] == "3.1.1.1" for a in non_chef_alerts))
            self.assertTrue(any(a["details"][0]["publicIpAddress"] == "4.1.1.1" for a in non_chef_alerts))

            self.assertEqual(3, len(chef_managed_alerts))
            self.assertTrue(any(a["details"][0]["publicIpAddress"] == "1.1.1.1" for a in chef_managed_alerts))
            self.assertTrue(any(a["details"][0]["publicIpAddress"] == "2.1.1.1" for a in chef_managed_alerts))
            self.assertTrue(any(a["details"][0]["publicIpAddress"] == "5.1.1.1" for a in chef_managed_alerts))
Example #20
0
    def test_old_query_params(self):
        uri = Mock()
        uri.query = "foo=bar&spam=ham"

        result = helpers._get_old_query_params(uri)
        self.assertEqual(result, ["foo=bar", "spam=ham"])
Example #21
0
    def test_old_query_params_with_equals(self):
        uri = Mock()
        uri.query = "foo=spam=ham"

        result = helpers._get_old_query_params(uri)
        self.assertEqual(result, ["foo=spam%3Dham"])
Example #22
0
 def test_unicode_input(self):
     query = Mock()
     unicode_payload = u"árvíztűrő tükörfúrógép"
     for answerer in answerers:
         query.query = u"{} {}".format(answerer.keywords[0], unicode_payload)
         self.assertTrue(isinstance(answerer.answer(query), list))
Example #23
0
 def test_query(self):
     client = Mock()
     client.query = Mock(return_value={})
     table = resources.Table(name="test", client=client)
     table.query({})
     client.query.assert_called_once_with(table, {})
Example #24
0
    def test_run(self, *mocks):

        eddaclient = Mock()

        def ret_list(args):
            return [
                {
                    "groupId": "sg-1",
                    "groupName": "group1",
                    "ipPermissions": [
                        {"fromPort": 22, "ipProtocol": "tcp", "ipRanges": ["0.0.0.0/0"], "toPort": 22},
                        {"fromPort": 0, "ipProtocol": "icmp", "ipRanges": ["0.0.0.0/0"], "toPort": -1},
                    ],
                },
                {
                    "groupId": "sg-2",
                    "groupName": "group2",
                    "ipPermissions": [{"fromPort": 139, "ipProtocol": "tcp", "ipRanges": ["0.0.0.0/0"], "toPort": 139}],
                },
                {"groupId": "sg-3", "groupName": "empty group"},
            ]

        def ret_machines(args):
            return [
                {
                    "imageId": "ami-1",
                    "instanceId": "a",
                    "publicIpAddress": "1.1.1.1",
                    "tags": [],
                    "securityGroups": [{"groupId": "sg-1", "groupName": "group1"}],
                },
                {
                    "imageId": "ami-1",
                    "instanceId": "b",
                    "publicIpAddress": "2.1.1.1",
                    "tags": [{"key": "Name", "value": "tag1"}],
                    "securityGroups": [
                        {"groupId": "sg-2", "groupName": "group2"},
                        {"groupId": "sg-1", "groupName": "group1"},
                    ],
                },
                {"imageId": "ami-2", "instanceId": "c", "publicIpAddress": "3.1.1.1", "tags": [], "securityGroups": []},
                {
                    "imageId": "ami-3",
                    "instanceId": "d",
                    "publicIpAddress": "4.1.1.1",
                    "tags": [],
                    "securityGroups": [{"groupId": "sg-4", "groupName": "group4"}],
                },
            ]

        m1 = Mock()
        m1.query = Mock(side_effect=ret_list)
        eddaclient.updateonly = Mock(return_value=m1)

        eddaclient.query = Mock(side_effect=ret_machines)
        self.plugin.init(eddaclient, self.config, {})

        # run the tested method
        self.assertEqual(
            self.plugin.run(),
            [
                {
                    "id": "sg-2 (group2)",
                    "plugin_name": "secgroups",
                    "details": [
                        {
                            "fromPort": 139,
                            "ipRanges": ["0.0.0.0/0"],
                            "toPort": 139,
                            "ipProtocol": "tcp",
                            "port_open": True,
                            "machines": ["b (2.1.1.1): tag1"],
                        }
                    ],
                }
            ],
        )

        m1.query.assert_has_calls([call("/api/v2/aws/securityGroups;_expand")])
        eddaclient.query.assert_has_calls([call("/api/v2/view/instances;_expand")])