コード例 #1
0
 def setUp(self, mock_user_login, mock_request):
     self.mock_user_login = _mock_user_login
     self.mock_request = mock_request
     self.conn = HealthBotClient(
         server='1.1.1.1',
         user='******',
         password='******').open()
コード例 #2
0
 def setUp(self, mock_user_login, mock_request):
     self.mock_user_login = _mock_user_login
     self.mock_request = mock_request
     self.mock_request().get.side_effect = self._mock_manager
     self.conn = HealthBotClient(
         server='1.1.1.1',
         user='******',
         password='******').open()
     self.conn.api_client.call_api = self._mock_manager
コード例 #3
0
 def setUp(self, mock_user_login, mock_request):
     self.mock_user_login = _mock_user_login
     self.mock_request = mock_request
     with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                new_callable=PropertyMock) as mock_ver:
         with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                    new_callable=PropertyMock) as mock_cnf:
             mock_ver.return_value = '2.1.0'
             mock_cnf.return_value = "https://1.1.1.1:8080/api/v1"
             self.conn = HealthBotClient(server='1.1.1.1',
                                         user='******',
                                         password='******').open()
コード例 #4
0
 def setUp(self, mock_user_login, mock_request):
     self.mock_user_login = _mock_user_login
     self.mock_request = mock_request
     self.mock_request().get.side_effect = self._mock_manager
     with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                new_callable=PropertyMock) as mock_ver:
         with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                    new_callable=PropertyMock) as mock_cnf:
             mock_ver.return_value = '4.0.0'
             mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
             self.conn = HealthBotClient(
                 server='1.1.1.1',
                 user='******',
                 password='******').open()
     self.conn.api_client.call_api = self._mock_manager
コード例 #5
0
 def test_context_manager(self, mock_user_logout, mock_user_login, mock_request):
     self.mock_user_login = _mock_user_login
     with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                new_callable=PropertyMock) as mock_ver:
         with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                    new_callable=PropertyMock) as mock_cnf:
             mock_ver.return_value = '2.0.1'
             mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
             with HealthBotClient(server='1.1.1.1', user='******',
                                  password='******') as conn:
                 self.assertEqual(conn.version, '2.0.1')
コード例 #6
0
class TestDatabase(unittest.TestCase):
    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch(
        'jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login'
    )
    def setUp(self, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        self.mock_request = mock_request
        self.conn = HealthBotClient(server='1.1.1.1',
                                    user='******',
                                    password='******').open()

    def tearDown(self) -> None:
        self.conn.close()

    def test_get_table(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.tsdb.get_table()
        self.assertEqual(obj.name, 'test')

    def _mock_manager(self, *args):
        class MockResponse(Response):
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

            def to_dict(self):
                return self.json_data

            def raise_for_status(self):
                return None

        if args[0] == 'https://1.1.1.1:8080/api/v1/data/database/table':
            return MockResponse({"name": "test", "type": "Field table"}, 200)
コード例 #7
0
class TestRules(unittest.TestCase):
    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch(
        'jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login'
    )
    def setUp(self, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        self.mock_request = mock_request
        with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                   new_callable=PropertyMock) as mock_ver:
            with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                       new_callable=PropertyMock) as mock_cnf:
                mock_ver.return_value = '2.1.0'
                mock_cnf.return_value = "https://1.1.1.1:8080/api/v1"
                self.conn = HealthBotClient(server='1.1.1.1',
                                            user='******',
                                            password='******').open()

    def tearDown(self) -> None:
        self.conn.close()

    def test_add_rule(self):
        self.mock_request().get.side_effect = self._mock_manager
        rs = RuleSchema(rule_name="hbez-fpc-heap-utilization")
        rs.description = "HealthBot EZ example"
        rs.synopsis = "Using python client for demo"
        rs.sensor = [{
            'description': 'Monitors FPC buffer, heap and cpu utilization',
            'iAgent': {
                'file': 'fpc-utilization.yml',
                'frequency': '30s',
                'table': 'FPCCPUHEAPutilizationTable'
            },
            'sensor_name': 'fpccpuheaputilization'
        }]
        rs.field = [{
            'constant': {
                'value': '{{fpc-buffer-usage-threshold}}'
            },
            'description': 'This field is for buffer usage threshold',
            'field_name': 'linecard-buffer-usage-threshold'
        }, {
            'constant': {
                'value': '{{fpc-cpu-usage-threshold}}'
            },
            'description': 'This field is for linecard cpu usage threshold',
            'field_name': 'linecard-cpu-usage-threshold'
        }, {
            'constant': {
                'value': '{{fpc-heap-usage-threshold}}'
            },
            'description': 'This field is for linecard heap usage threshold',
            'field_name': 'linecard-heap-usage-threshold'
        }]
        rs.keys = ['slot']
        rs.variable = [{
            'description': 'Linecard Buffer Memory usage threshold value',
            'name': 'fpc-buffer-usage-threshold',
            'type': 'int',
            'value': '80'
        }, {
            'description': 'Linecard CPU usage threshold value',
            'name': 'fpc-cpu-usage-threshold',
            'type': 'int',
            'value': '80'
        }, {
            'description': 'Linecard Heap Memory usage threshold value',
            'name': 'fpc-heap-usage-threshold',
            'type': 'int',
            'value': '80'
        }]
        rs.trigger = [{
            'description':
            'Sets health based on linecard buffer memory',
            'frequency':
            '60s',
            'synopsis':
            'Linecard buffer memory kpi',
            'term': [{
                'term_name':
                'is-buffer-memory-utilization-greater-than-threshold',
                'then': {
                    'status': {
                        'color':
                        'red',
                        'message':
                        'FPC buffer memory '
                        'utilization '
                        '($memory-buffer-utilization) '
                        'is over threshold '
                        '($linecard-buffer-usage-threshold)'
                    }
                },
                'when': {
                    'greater_than': [{
                        'left_operand':
                        '$memory-buffer-utilization',
                        'right_operand':
                        '$linecard-buffer-usage-threshold'
                    }]
                }
            }, {
                'term_name': 'buffer-utilization-less-than-threshold',
                'then': {
                    'status': {
                        'color': 'green'
                    }
                }
            }],
            'trigger_name':
            'fpc-buffer-memory-utilization'
        }, {
            'description':
            'Sets health based on linecard cpu utilization',
            'frequency':
            '60s',
            'synopsis':
            'Linecard cpu utilization kpi',
            'term': [{
                'term_name': 'is-cpu-utilization-greater-than-80',
                'then': {
                    'status': {
                        'color':
                        'red',
                        'message':
                        'FPC CPU utilization '
                        '($cpu-total) is over '
                        'threshold '
                        '($linecard-cpu-usage-threshold)'
                    }
                },
                'when': {
                    'greater_than': [{
                        'left_operand': '$cpu-total',
                        'right_operand': '$linecard-cpu-usage-threshold',
                        'time_range': '180s'
                    }]
                }
            }, {
                'term_name': 'cpu-utilization-less-than-threshold',
                'then': {
                    'status': {
                        'color': 'green'
                    }
                }
            }],
            'trigger_name':
            'fpc-cpu-utilization'
        }, {
            'description':
            'Sets health based on linecard heap memory '
            'utilization',
            'frequency':
            '60s',
            'synopsis':
            'Linecard heap memory kpi',
            'term': [{
                'term_name':
                'is-heap-memory-utilization-greater-than-threshold',
                'then': {
                    'status': {
                        'color':
                        'red',
                        'message':
                        'FPC heap memory '
                        'utilization '
                        '($memory-heap-utilization) '
                        'is over threshold '
                        '($linecard-heap-usage-threshold)'
                    }
                },
                'when': {
                    'greater_than': [{
                        'left_operand':
                        '$memory-heap-utilization',
                        'right_operand':
                        '$linecard-heap-usage-threshold'
                    }]
                }
            }, {
                'term_name': 'heap-memory-utilization-less-than-threshold',
                'then': {
                    'status': {
                        'color': 'green'
                    }
                }
            }],
            'trigger_name':
            'fpc-heap-memory-utilization'
        }]

        self.assertTrue(self.conn.rule.add('external', schema=rs))

    def test_add_rule_without_schema(self):
        self.assertTrue(
            self.conn.rule.add(rule_name="hbez-fpc-heap-utilization",
                               topic_name='test'))

    def test_schema_check(self):
        self.assertTrue(
            self.conn.rule.add(rule_name="hbez-fpc-heap-utilization",
                               topic_name='test'))

    def test_get_rule(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.rule.get(topic_name='external',
                                 rule_name="hbez-fpc-heap-utilization")
        self.assertEqual(ret.description, 'HealthBot EZ example')

    def test_get_rules(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.rule.get(topic_name='external')
        self.assertEqual(ret[0].rule_name, 'interface-info')

    def test_delete_rule(self):
        ret = self.conn.rule.delete(topic_name='external',
                                    rule_name="hbez-fpc-heap-utilization")
        self.assertTrue(ret)
        self.assertEqual(self.mock_request().mock_calls[2][0], 'delete')

    def test_update_rule(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.rule.get(topic_name='external',
                                 rule_name="hbez-fpc-heap-utilization")
        ret.keys = ['slot']
        self.conn.rule.update(topic_name='external', schema=ret)
        self.assertEqual(self.mock_request().mock_calls[3][2]['json']['keys'],
                         ['slot'])

    def test_get_topic(self):
        self.mock_request().get.side_effect = self._mock_manager
        topic = self.conn.topic.get(topic_name='external')
        self.assertEqual(topic.topic_name, 'external')

    def test_get_topics(self):
        self.mock_request().get.side_effect = self._mock_manager
        topics = self.conn.topic.get()
        self.assertEqual(topics[0].description,
                         'Monitors the chassis temperatures of whole chassis')

    def _mock_manager(self, *args):
        class MockResponse(Response):
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

            def to_dict(self):
                return self.json_data

            def raise_for_status(self):
                return None

        if args[0] == 'https://1.1.1.1:8080/api/v1/topic/external/?working=true':
            obj = MockResponse(
                {
                    "rule": [{
                        "field":
                        [{
                            "description":
                            "admin status",
                            "field-name":
                            "admin",
                            "sensor": [{
                                "path": "admin",
                                "sensor-name": "phyport"
                            }],
                            "type":
                            "string"
                        }, {
                            "field-name": "name",
                            "sensor": [{
                                "path": "name",
                                "sensor-name": "phyport"
                            }],
                            "type": "string"
                        }, {
                            "description": "oper status",
                            "field-name": "oper",
                            "sensor": [{
                                "path": "oper",
                                "sensor-name": "phyport"
                            }],
                            "type": "string"
                        }],
                        "keys": ["name"],
                        "rule-name":
                        "interface-info",
                        "variable": [{
                            "name": "interface_name",
                            "type": "sensor-argument"
                        }]
                    }],
                    "sub-topics": [],
                    "topic-name":
                    "external"
                }, 200)
            return obj
        elif args[
                0] == 'https://1.1.1.1:8080/api/v1/topic/external/rule/hbez-fpc-heap-utilization/?working=true':
            obj = MockResponse(
                {
                    "description":
                    "HealthBot EZ example",
                    "field": [
                        {
                            "constant": {
                                "value": "{{fpc-buffer-usage-threshold}}"
                            },
                            "description":
                            "This field is for buffer usage threshold",
                            "field-name": "linecard-buffer-usage-threshold"
                        },
                        {
                            "constant": {
                                "value": "{{fpc-cpu-usage-threshold}}"
                            },
                            "description":
                            "This field is for linecard cpu usage threshold",
                            "field-name": "linecard-cpu-usage-threshold"
                        },
                    ],
                    "keys": ["slot"],
                    "rule-name":
                    "hbez-fpc-heap-utilization",
                    "sensor": [{
                        "description":
                        "Monitors FPC buffer, heap and cpu utilization",
                        "iAgent": {
                            "file": "fpc-utilization.yml",
                            "frequency": "30s",
                            "table": "FPCCPUHEAPutilizationTable"
                        },
                        "sensor-name": "fpccpuheaputilization"
                    }],
                    "synopsis":
                    "Using python client for demo",
                    "trigger": [
                        {
                            "description":
                            "Sets health based on linecard buffer memory",
                            "frequency": "60s",
                            "synopsis": "Linecard buffer memory kpi",
                            "trigger-name": "fpc-buffer-memory-utilization"
                        },
                        {
                            "description":
                            "Sets health based on linecard cpu utilization",
                            "frequency": "60s",
                            "synopsis": "Linecard cpu utilization kpi",
                            "trigger-name": "fpc-cpu-utilization"
                        },
                    ],
                    "variable": [{
                        "description":
                        "Linecard Buffer Memory usage threshold value",
                        "name": "fpc-buffer-usage-threshold",
                        "type": "int",
                        "value": "80"
                    }]
                }, 200)
            return obj
        elif args[0] == 'https://1.1.1.1:8080/api/v1/topics':
            return MockResponse(
                {
                    "topic": [{
                        "description":
                        "Monitors the chassis temperatures of whole chassis",
                        "topic-name":
                        "external",
                        "rule": [{
                            "description":
                            "HealthBot EZ example",
                            "field": [
                                {
                                    "constant": {
                                        "value":
                                        "{{fpc-buffer-usage-threshold}}"
                                    },
                                    "description":
                                    "This field is for buffer usage threshold",
                                    "field-name":
                                    "linecard-buffer-usage-threshold"
                                },
                                {
                                    "constant": {
                                        "value": "{{fpc-cpu-usage-threshold}}"
                                    },
                                    "description":
                                    "This field is for linecard cpu usage threshold",
                                    "field-name":
                                    "linecard-cpu-usage-threshold"
                                },
                            ],
                            "keys": ["slot"],
                            "rule-name":
                            "hbez-fpc-heap-utilization",
                            "sensor": [{
                                "description":
                                "Monitors FPC buffer, heap and cpu utilization",
                                "iAgent": {
                                    "file": "fpc-utilization.yml",
                                    "frequency": "30s",
                                    "table": "FPCCPUHEAPutilizationTable"
                                },
                                "sensor-name": "fpccpuheaputilization"
                            }],
                            "synopsis":
                            "Using python client for demo",
                            "trigger": [
                                {
                                    "description":
                                    "Sets health based on linecard buffer memory",
                                    "frequency": "60s",
                                    "synopsis": "Linecard buffer memory kpi",
                                    "trigger-name":
                                    "fpc-buffer-memory-utilization"
                                },
                                {
                                    "description":
                                    "Sets health based on linecard cpu utilization",
                                    "frequency": "60s",
                                    "synopsis": "Linecard cpu utilization kpi",
                                    "trigger-name": "fpc-cpu-utilization"
                                },
                            ],
                            "variable": [{
                                "description":
                                "Linecard Buffer Memory usage threshold value",
                                "name": "fpc-buffer-usage-threshold",
                                "type": "int",
                                "value": "80"
                            }]
                        }]
                    }]
                }, 200)
        return MockResponse(None, 404)
コード例 #8
0
class TestAdministration(unittest.TestCase):

    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch('jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login')
    def setUp(self, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        self.mock_request = mock_request
        self.mock_request().get.side_effect = self._mock_manager
        self.conn = HealthBotClient(
            server='1.1.1.1',
            user='******',
            password='******').open()
        self.conn.api_client.call_api = self._mock_manager

    def tearDown(self) -> None:
        self.conn.close()

    def test_administration_group_get(self):
        ret = self.conn.administration.group.get(group_name="hboperator")
        self.assertEqual(ret.group_name, 'hboperator')

    def test_administration_group_update(self):
        userid = self.conn.administration.user.get_userid_from_user_name(
            user_name="xxx")
        schema = Groups(
            group_name='hboperator',
            group_description="testing HbEZ",
            roles=[
                GroupgroupidRoles(
                    role_id='xxx-xx-xxx',
                    role_name='token:write')],
            users=[
                AssociatedUserSchemaInner(
                    user_id=userid,
                    user_name="xxx")])
        self.assertTrue(self.conn.administration.group.add(schema))
        schema = self.conn.administration.group.get(group_name="hboperator")
        schema.users.append(
            AssociatedUserSchemaInner(
                user_id=self.conn.administration.user.get_userid_from_user_name(
                    user_name="yyy"),
                user_name="yyy"))
        self.assertTrue(self.conn.administration.group.update(schema=schema))

    def test_administration_group_get_all(self):
        ret = self.conn.administration.group.get()
        self.assertEqual(ret[0].group_name, 'hboperator')

    def test_administration_user_get(self):
        ret = self.conn.administration.user.get(user_name="xxx")
        print(ret)
        self.assertEqual(ret.user_name, 'xxx')

    def test_administration_user_add(self):
        self.conn.administration.user._admin_api.create_users = self._mock_manager
        from jnpr.healthbot import UserSchema, UserSchemaGroups
        group_id = self.conn.administration.group.get_groupid_from_group_name(
            'hboperator')
        user = UserSchema(
            user_name="xxx",
            first_name="xxx",
            last_name="xxx",
            password="******",
            email="*****@*****.**",
            active=True,
            groups=[
                UserSchemaGroups(
                    group_id=group_id,
                    group_name="hboperator")])
        self.assertTrue(self.conn.administration.user.add(user))

    def test_administration_user_update(self):
        self.conn.administration.user._admin_api.create_users = self._mock_manager
        from jnpr.healthbot import UserSchema, UserSchemaGroups
        group_id = self.conn.administration.group.get_groupid_from_group_name(
            'hboperator')
        user = UserSchema(
            user_name="xxx",
            first_name="xxx",
            last_name="xxx",
            password="******",
            email="*****@*****.**",
            active=True,
            groups=[
                UserSchemaGroups(
                    group_id=group_id,
                    group_name="hboperator")])
        self.conn.administration.user.add(user)
        obj = self.conn.administration.user.get(user_name="xxx")
        obj.last_name = "Kumar"
        self.assertTrue(self.conn.administration.user.update(schema=obj))

    def test_administration_group_delete(self):
        self.assertTrue(
            self.conn.administration.group.delete(
                group_name='hboperator'))

    def test_administration_user_delete(self):
        self.assertTrue(self.conn.administration.user.delete(user_name='xxx'))

    def test_administration_roles_get(self):
        ret = self.conn.administration.role.get(role_name='data-store:write')
        self.assertEqual(ret.role_id, 'xxx-xx-xx-xxx-xxx')

    def _mock_manager(self, *args, **kwargs):
        class MockResponse(Response):
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

            def to_dict(self):
                return self.json_data

            def raise_for_status(self):
                return None

        if args == () and 'users' in kwargs:
            return []
        elif args[0] == '/user/{userid}/' and args[1] == 'GET':
            from jnpr.healthbot import InlineResponse2004
            return InlineResponse2004(**{'active': True,
                                         'email': '*****@*****.**',
                                         'first_name': 'xxx',
                                         'last_name': 'kr12',
                                         'user_id': 'xxx-xx-xx-xxx-xxxx',
                                         'user_name': 'xxx'})
        elif args[0] == '/user/{userid}/' and args[1] == 'DELETE':
            return None
        elif args[0] == '/user/' and args[1] == 'GET':
            from jnpr.healthbot import InlineResponse2002
            return [InlineResponse2002(**{'active': True,
                                          'email': '*****@*****.**',
                                          'first_name': 'xxx',
                                          'last_name': 'kr12',
                                          'user_id': 'xxx-xx-xx-xxx-xxxx',
                                          'user_name': 'xxx'}),
                    InlineResponse2002(**{'active': True,
                                          'email': '*****@*****.**',
                                          'first_name': 'yyy',
                                          'last_name': 'dan',
                                          'user_id': 'yyy-xx-xx-xxx-yyyy',
                                          'user_name': 'yyy'})
                    ]
        elif args[0] == '/group/' and args[1] == 'GET':
            from jnpr.healthbot import InlineResponse2008
            return [InlineResponse2008(**{'group_description': '',
                                          'group_id': 'xx-xx-xx-xxx-xxxx',
                                          'group_name': 'hboperator',
                                          'roles': None,
                                          'users': None})]
        elif args[0] == '/group/{groupid}/' and args[1] == 'DELETE':
            return None
        elif args[0] == '/group/{groupid}/' and args[1] == 'GET':
            return Groups(**{'group_description': '',
                             'group_name': 'hboperator',
                             'roles': [{'roleId': 'xx-xxx-xxx',
                                        'roleName': 'token:write'},
                                       {'roleId': 'xx-xxy-xxx',
                                        'roleName': 'login:write'},
                                       {'roleId': 'xx-xxz-xxx',
                                        'roleName': 'user-profile:read'},
                                       {'roleId': 'xx-xxi-xxx',
                                        'roleName': 'logout:write'},
                                       {'roleId': 'xx-xxa-xxx',
                                        'roleName': 'first-login:write'}, ],
                             'users': [{'userId': 'xx-yyy-xxx',
                                        'userName': '******'}]})
        elif args[0] == '/role/':
            from jnpr.healthbot import RoleSchemaInner
            return [{'roleId': 'xxx-xx-xx-xxx-xxx',
                     'roleName': 'data-store:write'}]
        return MockResponse(None, 404)
コード例 #9
0
from pprint import pprint
from jnpr.healthbot.swagger.models.hb_graphs_query import HbGraphsQuery
from jnpr.healthbot.swagger.models.hb_graphs import HbGraphs
from jnpr.healthbot import HealthBotClient

ip = 'ip'
gui_username = '******'
gui_password = '******'

with HealthBotClient(ip, gui_username, gui_password, port=8080) as hb:
    # Adding a new canvas
    # group_name, device_name, measurement_name, field_name are compulsory fields here
    query1 = HbGraphsQuery(group_name='dg-junos',
                           device_name="d2",
                           measurement_name="system.commit/commit-history",
                           transformation=None,
                           field_name="l1-threshold",
                           field_aggregation="mean",
                           where=[{
                               'key': "comment",
                               "operator": '=',
                               "value": "new"
                           }],
                           group_by_interval="1s",
                           group_by_fill="fill(null)",
                           group_by_tag_key=[])
    # Multiple queries can be present for a graph
    # graph_name, graph_type, time_range are compulsory here
    graph1 = HbGraphs(graph_name="graph1",
                      graph_description=None,
                      graph_type="Heatmap",
コード例 #10
0
class TestPlaybooks(unittest.TestCase):

    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch('jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login')
    def setUp(self, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        self.mock_request = mock_request
        with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                   new_callable=PropertyMock) as mock_ver:
            with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                       new_callable=PropertyMock) as mock_cnf:
                mock_ver.return_value = '4.0.0'
                mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
                self.conn = HealthBotClient(
                    server='1.1.1.1',
                    user='******',
                    password='******').open()

    def tearDown(self) -> None:
        self.conn.close()

    def test_add_playbook_using_schema_check_existance(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbs = PlaybookSchema(playbook_name="automation-coredump-pb")
        pbs.description = "HbEZ Demo Examples"
        pbs.synopsis = 'fpc status'
        pbs.rules = ['hbez/hbez-fpc-heap-utilization']
        ret = self.conn.playbook.add(pbs)
        self.assertTrue(ret)

    def test_add_playbook_using_schema(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbs = PlaybookSchema(playbook_name="testing")
        pbs.description = "HbEZ Demo Examples"
        pbs.rules = ['hbez/hbez-fpc-heap-utilization']
        self.assertTrue(self.conn.playbook.add(pbs))

    def test_delete_playbook(self):
        self.assertTrue(
            self.conn.playbook.delete(
                playbook_name="testing"))

    def test_get_playbook(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.playbook.get(
            playbook_name="automation-coredump-pb")
        self.assertEqual(obj.rules, [
            "protocol-automation-coredumps/check-coredumps"
        ])

    def test_update_playbook(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.playbook.get(
            playbook_name="automation-coredump-pb")
        obj.description = "testing"
        self.conn.playbook.update(obj)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['description'],
            "testing")

    def test_get_playbooks(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.playbook.get()
        self.assertGreaterEqual(len(obj), 1)

    def test_playbook_instance_builder_with_no_variable(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbb = PlayBookInstanceBuilder(
            self.conn, 'automation-coredump-pb', 'HbEZ-instance',
            'Core')
        pbb.apply()
        self.assertEqual(self.mock_request().mock_calls[5][0], 'put')
        self.assertEqual(
            self.mock_request().mock_calls[5][1][0],
            'https://1.1.1.1:8080/api/v2/config/device-group/Core')

    def test_playbook_instance_builder_delete(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbb = PlayBookInstanceBuilder(
            self.conn, 'automation-coredump-pb', 'HbEZ-instance',
            'Core')
        pbb.delete()
        self.assertEqual(self.mock_request().mock_calls[6][0], 'put')
        self.assertEqual(
            self.mock_request().mock_calls[6][1][0],
            'https://1.1.1.1:8080/api/v2/config/device/vmx')
        self.assertEqual(
            self.mock_request().mock_calls[10][1][0],
            'https://1.1.1.1:8080/api/v2/config/device-group/Core')

    def test_playbook_apply_commit(self):
        self.mock_request().get.side_effect = self._mock_manager
        with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                   new_callable=PropertyMock) as mock_cnf:
            mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
            pbb = PlayBookInstanceBuilder(
                self.conn, 'automation-coredump-pb', 'HbEZ-instance',
                'Core')
            pbb.apply(commit=True)
            self.assertEqual(self.mock_request().mock_calls[9][0], 'post')
            self.assertEqual(
                self.mock_request().mock_calls[9][1][0],
                'https://1.1.1.1:8080/api/v2/config/configuration')

    def test_playbook_instance_builder_with_no_device_group(self):
        from jnpr.healthbot.exception import NotFoundError
        self.mock_request().get.side_effect = self._mock_manager
        pbb = PlayBookInstanceBuilder(
            self.conn, 'automation-coredump-pb', 'xyz', 'real')
        self.assertRaises(NotFoundError, pbb.apply)

    def test_playbook_instance_builder_with_variable(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbb = PlayBookInstanceBuilder(
            self.conn,
            'forwarding-table-summary',
            'HbEZ-instance',
            'Core')
        routesummary_fib_summary = pbb.rule_variables["protocol.routesummary/check-fib-summary"]
        routesummary_fib_summary.route_count_threshold = 200
        routesummary_fib_summary.route_address_family = 'abc'
        pbb.apply()
        self.assertEqual(self.mock_request().mock_calls[6][0], 'put')
        self.assertEqual(
            self.mock_request().mock_calls[6][1][0],
            'https://1.1.1.1:8080/api/v2/config/device-group/Core')

    def test_playbook_instance_builder_with_variable_per_device(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbb = PlayBookInstanceBuilder(
            self.conn,
            'forwarding-table-summary',
            'HbEZ-instance',
            'Core')
        routesummary_fib_summary = pbb.rule_variables["protocol.routesummary/check-fib-summary"]
        routesummary_fib_summary.route_count_threshold = 200
        routesummary_fib_summary.route_address_family = 'abc'
        pbb.apply(device_ids=['vmx'])
        self.assertEqual(self.mock_request().mock_calls[7][0], 'put')
        self.assertEqual(
            self.mock_request().mock_calls[7][1][0],
            'https://1.1.1.1:8080/api/v2/config/device/vmx')

    def test_playbook_instance_builder_with_non_existing_device(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbb = PlayBookInstanceBuilder(
            self.conn,
            'forwarding-table-summary',
            'HbEZ-instance',
            'Core')
        routesummary_fib_summary = pbb.rule_variables["protocol.routesummary/check-fib-summary"]
        routesummary_fib_summary.route_count_threshold = 200
        routesummary_fib_summary.route_address_family = 'abc'
        self.assertRaises(RuntimeError, pbb.apply, device_ids=['fake'])

    def test_clear(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbb = PlayBookInstanceBuilder(
            self.conn,
            'forwarding-table-summary',
            'HbEZ-instance',
            'Core')
        routesummary_fib_summary = pbb.rule_variables["protocol.routesummary/check-fib-summary"]
        routesummary_fib_summary.route_count_threshold = 200
        routesummary_fib_summary.route_address_family = 'abc'
        pbb.clear()
        routesummary_fib_summary = pbb.rule_variables["protocol.routesummary/check-fib-summary"]
        self.assertEqual(
            routesummary_fib_summary.route_count_threshold,
            '10000')

    def test_playbook_schema_setter(self):
        self.mock_request().get.side_effect = self._mock_manager
        pbb = PlayBookInstanceBuilder(
            self.conn,
            'forwarding-table-summary',
            'HbEZ-instance',
            'Core')
        with self.assertRaises(RuntimeError):
            pbb.playbook_schema = 30

    def test_get_playbook_schema_error(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.assertRaises(AttributeError, PlayBookInstanceBuilder, self.conn,
                          'dummy', 'HbEZ-instance', 'Core')

    def _mock_manager(self, *args):
        class MockResponse(Response):
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

            def to_dict(self):
                return self.json_data

            def raise_for_status(self):
                return None

        if args[0] == 'https://1.1.1.1:8080/api/v2/config/playbook/automation-coredump-pb/?working=true':
            obj = MockResponse({
                "playbook-name": "automation-coredump-pb",
                "rules": [
                    "protocol-automation-coredumps/check-coredumps"
                ]
            }, 200)
            return obj
        if args[0] == 'https://1.1.1.1:8080/api/v2/config/topic/protocol-automation-coredumps/rule/check-coredumps/?working=true':
            obj = MockResponse({"description": "This rule will monitor for the automation coredumps",
                                "field": [{"description": "Actual coredump filename",
                                           "field-name": "coredump-filename",
                                           "formula": {"user-defined-function": {"argument": [{"argument": "message",
                                                                                               "value": "$coredump-message"}],
                                                                                 "function-name": "get-core-filename-from-message"}},
                                           "type": "string"},
                                          {"description": "The actual syslog that appears when a coredump happens",
                                           "field-name": "coredump-message",
                                           "sensor": [{"path": "/junos/events/event/message",
                                                       "sensor-name": "coredump-detectors",
                                                       "where": [{"query": "/junos/events/event/message =~ /.*Core and context for (eventd|cscript).*/"}]}],
                                           "type": "string"},
                                          {"description": "Timestamp of the coredump as registered by the telemetry sensor",
                                           "field-name": "coredump-timestamp",
                                           "sensor": [{"path": "/junos/events/event/timestamp/seconds",
                                                       "sensor-name": "coredump-detectors"}],
                                           "type": "string"}],
                                "keys": ["coredump-message"],
                                "rule-name": "check-coredumps",
                                "sensor": [{"open-config": {"frequency": "0s",
                                                            "sensor-name": "/junos/events/event[id='SYSTEM']"},
                                            "sensor-name": "coredump-detectors"}],
                                "synopsis": "To monitor automation coredumps",
                                "trigger": [{"frequency": "15s",
                                             "term": [{"term-name": "core-generated",
                                                       "then": {"status": {"color": "red",
                                                                           "message": "Coredump was seen: $coredump-message"},
                                                                "user-defined-action": [{"argument": [{"argument": "local_dir_name",
                                                                                                       "value": "coredumps"}],
                                                                                         "function-name": "get-automation-traces"},
                                                                                        {"argument": [{"argument": "local_dir_name",
                                                                                                       "value": "coredump"},
                                                                                                      {"argument": "remote_dir_name",
                                                                                                       "value": "$coredump-filename"}],
                                                                                         "function-name": "get-file-from-device"},
                                                                                        {"argument": [{"argument": "local_dir_name",
                                                                                                       "value": "coredump"},
                                                                                                      {"argument": "remote_dir_name",
                                                                                                       "value": "/var/log/* /var/tmp/*"}],
                                                                                         "function-name": "get-log-file-from-device"}]},
                                                       "when": {"matches-with": [{"left-operand": "$coredump-message",
                                                                                  "right-operand": ".*Core and context.*",
                                                                                  "time-range": "30s"}]}},
                                                      {"term-name": "Core-not-generated",
                                                       "then": {"status": {"color": "green",
                                                                           "message": "No core found"}}}],
                                             "trigger-name": "core-generated"}]},
                               200)
            return obj
        if args[0] == 'https://1.1.1.1:8080/api/v2/config/playbooks/?working=true':
            obj = MockResponse({"playbook": [{"playbook-name": "netsvc-playbook",
                                              "rules": ["chassis.networkservices/netsvc-rule"]},
                                             {"playbook-name": "phyport",
                                              "rules": ["external/interface-info"]},
                                             {"playbook-name": "automation-coredump-pb",
                                              "rules": ["protocol-automation-coredumps/check-coredumps"]},
                                             {"description": "This playbook help to collect eventd debug logs",
                                              "playbook-name": "eventd-debug-collection",
                                              "rules": ["protocol-eventd-debug/collect-debugs"],
                                              "synopsis": "Collect eventd logs"}]},
                               200)
            return obj
        if args[0] == 'https://1.1.1.1:8080/api/v2/config/topic/protocol.routesummary/rule/check-fib-summary/?working=true':
            obj = MockResponse({
                "description": "Collects forwarding-table's total-route-count of each protocol and sets dynamic thresholds and notify anomaly when route count is abnormal",
                "field": [
                    {
                        "description": "Address family name to be monitored",
                        "field-name": "address-family",
                        "sensor": [
                            {
                                "path": "address-family",
                                "sensor-name": "fib-sensor",
                                "where": [
                                    {
                                        "query": "address-family =~ /^{{route-address-family}}$/"
                                    }
                                ]
                            }
                        ],
                        "type": "string"
                    },
                    {
                        "description": "Detects anamoly dynamically using kmeans algorithm",
                        "field-name": "dt-route-count",
                        "formula": {
                            "dynamic-threshold": {
                                "algorithm": "3sigma",
                                "field-name": "$route-count",
                                "learning-period": "7d",
                                "pattern-periodicity": "1h"
                            }
                        },
                        "type": "integer"
                    },
                    {
                        "description": "Route table type to be monitored",
                        "field-name": "route-table-type",
                        "sensor": [
                            {
                                "path": "route-table-type",
                                "sensor-name": "fib-sensor",
                                "where": [
                                    {
                                        "query": "route-table-type =~ /^{{table-type}}$/"
                                    }
                                ]
                            }
                        ],
                        "type": "string"
                    },
                    {
                        "description": "Route table name to be monitored",
                        "field-name": "table-name",
                        "sensor": [
                            {
                                "path": "table-name",
                                "sensor-name": "fib-sensor",
                                "where": [
                                    {
                                        "query": "table-name =~ /^{{route-table-name}}$/"
                                    }
                                ]
                            }
                        ],
                        "type": "string"
                    },
                    {
                        "constant": {
                            "value": "{{route-count-threshold}}"
                        },
                        "description": "Route count static threshold",
                        "field-name": "threshold",
                        "type": "integer"
                    }
                ],
                "keys": [
                    "address-family",
                    "route-table-type",
                    "table-name"
                ],
                "rule-name": "check-fib-summary",
                "sensor": [
                    {
                        "description": "iAgent sensor collect forwarding-table route-count stats from network device",
                        "iAgent": {
                            "file": "fib.yml",
                            "frequency": "10m",
                            "table": "FibSummaryTable"
                        },
                        "sensor-name": "fib-sensor",
                        "synopsis": "FIB iAgent sensor definition"
                    }
                ],
                "synopsis": "Forwarding-table protocols routes statistics analyzer",
                "trigger": [
                    {
                        "frequency": "10m",
                        "term": [
                            {
                                "term-name": "is-route-count-abnormal",
                                "then": {
                                    "status": {
                                        "color": "red",
                                        "message": "Route count of $table-name of $address-family of $route-table-type is ($route-count) abnormal"
                                    }
                                },
                                "when": {
                                    "greater-than-or-equal-to": [
                                        {
                                            "left-operand": "$route-count",
                                            "right-operand": "$threshold",
                                            "time-range": "30m"
                                        }
                                    ]
                                }
                            },
                            {
                                "term-name": "is-route-count-above-dt",
                                "then": {
                                    "status": {
                                        "color": "yellow",
                                        "message": "Route count of $table-name of $address-family of $route-table-type is ($route-count) is above dynamic threshold"
                                    }
                                },
                                "when": {
                                    "equal-to": [
                                        {
                                            "left-operand": "$dt-route-count",
                                            "right-operand": "1",
                                            "time-range": "30m"
                                        }
                                    ]
                                }
                            },
                            {
                                "term-name": "route-count-normal",
                                "then": {
                                    "status": {
                                        "color": "green",
                                        "message": "Route count of $table-name of $address-family of $route-table-type is ($route-count) normal"
                                    }
                                }
                            }
                        ],
                        "trigger-name": "fib-route-count"
                    }
                ],
                "variable": [
                    {
                        "description": "address-family names to monitor, regular expression, eg 'Internet|Internet6|MPLS|VPLS'",
                        "name": "route-address-family",
                        "type": "string",
                        "value": ".+"
                    },
                    {
                        "description": "Forwarding table's each protocol's route count threshold",
                        "name": "route-count-threshold",
                        "type": "int",
                        "value": "10000"
                    },
                    {
                        "description": "route table names to monitor, regular expression, eg 'default.inet|default.inet6|vpn_0.inet'",
                        "name": "route-table-name",
                        "type": "string",
                        "value": ".+"
                    },
                    {
                        "description": "route table types to monitor, regular expression, eg 'perm|intf|user'",
                        "name": "table-type",
                        "type": "string",
                        "value": ".+"
                    }
                ]
            },
                200)
            return obj
        if args[0] == 'https://1.1.1.1:8080/api/v2/config/playbook/forwarding-table-summary/?working=true':
            obj = MockResponse({
                "description": "Playbook monitors forwarding-table's each protocol's route count and notifies anomaly when route count is above static or dynamic threshold",
                "playbook-name": "forwarding-table-summary",
                "rules": [
                    "protocol.routesummary/check-fib-summary"
                ],
                "synopsis": "Forwarding table and protocol routes key performance indicators"
            }, 200)
            return obj
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/device-group/Core/?working=true':
            return MockResponse({"description": "testing",
                                 "device-group-name": "Core",
                                 "devices": ["vmx"],
                                 "native-gpb": {"ports": [22000]},
                                 "notification": {},
                                 "playbooks": ["eventd-debug-collection",
                                               "eventd-kpis-playbook",
                                               'automation-coredump-pb'],
                                 "reports": [],
                                 "variable": [{"@": {"changed-seconds": 1564722219},
                                               "instance-id": "HbEZ-instance",
                                               "playbook": "automation-coredump-pb",
                                               "rule": "x/y",
                                               "variable-value": []}]},
                                200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/device/vmx/?working=true':
            return MockResponse({
                "authentication": {
                    "password": {
                        "password": "******",
                        "username": "******"
                    }
                },
                "device-id": "vmx",
                "host": "10.221.136.140",
                "open-config": {
                    "port": 32767
                },
                "system-id": "testing",
                "variable": [{"@": {"changed-seconds": 1564722219},
                                               "instance-id": "HbEZ-instance",
                                               "playbook": "automation-coredump-pb",
                                               "rule": "x/y",
                                               "variable-value": []}],
                "vendor": {
                    "juniper": {
                        "operating-system": "junos"
                    }
                }
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/playbook/testing/?working=true':
            obj = MockResponse({
                "detail": "Playbook not found",
                "status": 404
            }, 404)
            return obj
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/device/vmx/?working=true':
            return MockResponse({
                "authentication": {
                    "password": {
                        "password": "******",
                        "username": "******"
                    }
                },
                "device-id": "vmx",
                "host": "10.221.xxx.xxx",
                "open-config": {
                    "port": 32767
                },
                "system-id": "testing",
                "variable": [],
                "vendor": {
                    "juniper": {
                        "operating-system": "junos"
                    }
                }
            }, 200)
        return MockResponse(None, 404)
コード例 #11
0
class TestSettings(unittest.TestCase):

    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch('jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login')
    def setUp(self, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        self.mock_request = mock_request
        self.mock_request().get.side_effect = self._mock_manager
        with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                   new_callable=PropertyMock) as mock_ver:
            with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                       new_callable=PropertyMock) as mock_cnf:
                mock_ver.return_value = '4.0.0'
                mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
                self.conn = HealthBotClient(
                    server='1.1.1.1',
                    user='******',
                    password='******').open()
        self.conn.api_client.call_api = self._mock_manager

    def tearDown(self) -> None:
        self.conn.close()

    def test_add_notification(self):
        ns = NotificationSchema(notification_name='HbEZ-notification')
        ns.description = "example of adding notification via API"
        nss = NotificationSchemaSlack(channel="HbEZ", url='https://testing')
        ns.slack = nss
        self.assertTrue(self.conn.settings.notification.add(ns))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/notification/HbEZ-notification')
        # add without schema
        self.assertTrue(
            self.conn.settings.notification.add(
                notification_name='HbEZ-notification',
                description="example of adding notification via API"))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/notification/HbEZ-notification')

    def test_add_scheduler(self):
        sc = SchedulerSchema(
            name='HbEZ-schedule',
            repeat={
                'every': 'week'},
            start_time="2019-07-22T05:32:23Z")
        self.assertTrue(self.conn.settings.scheduler.add(sc))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/system-settings/scheduler/HbEZ-schedule')
        # add without schema
        self.assertTrue(
            self.conn.settings.scheduler.add(
                name='HbEZ-schedule',
                repeat={
                    'every': 'week'},
                start_time="2019-07-22T05:32:23Z"))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/system-settings/scheduler/HbEZ-schedule')

    def test_add_destinaton(self):
        ds = DestinationSchema(
            name='HbEZ-destination',
            email={
                'id': '*****@*****.**'})
        self.assertTrue(self.conn.settings.destination.add(ds))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/system-settings/report-generation/destination/HbEZ-destination')
        # add without schema
        self.assertTrue(self.conn.settings.destination.add(
            name='HbEZ-destination', email={'id': '*****@*****.**'}))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/system-settings/report-generation/destination/HbEZ-destination')

    def test_add_report(self):
        rs = ReportSchema(
            name="HbEZ-report",
            destination=['HbEZ-destination'],
            format="html",
            schedule=["HbEZ-schedule"])
        self.assertTrue(self.conn.settings.report.add(rs))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/system-settings/report-generation/report/HbEZ-report')
        # add without schema
        self.assertTrue(
            self.conn.settings.report.add(
                name="HbEZ-report",
                destination=['HbEZ-destination'],
                format="html",
                schedule=["HbEZ-schedule"]))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/system-settings/report-generation/report/HbEZ-report')

    def test_add_retention_policy(self):
        rps = RetentionPolicySchema(retention_policy_name='HbEZ-testing')
        self.assertTrue(
            self.conn.settings.retention_policy.add(rps))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/retention-policy/HbEZ-testing')
        # without creating schema
        self.assertTrue(
            self.conn.settings.retention_policy.add(
                retention_policy_name='HbEZ-testing'))
        self.assertEqual(self.mock_request().mock_calls[2][0], 'post')
        self.assertEqual(
            self.mock_request().mock_calls[2][1][0],
            'https://1.1.1.1:8080/api/v2/config/retention-policy/HbEZ-testing')

    def test_get_notification(self):
        ns = self.conn.settings.notification.get(
            notification_name='HbEZ-notification')
        self.assertEqual(
            ns.description,
            "example of adding notification via API")
        self.assertEqual(ns.notification_name, "HbEZ-notification")

    def test_get_notification_error(self):
        self.assertRaises(
            ValueError,
            self.conn.settings.notification.get,
            notification_name='error')

    def test_get_scheduler(self):
        sc = self.conn.settings.scheduler.get(name='HbEZ-schedule')
        self.assertEqual(sc.repeat, {
            "every": "week"
        })

    def test_get_destination(self):
        ds = self.conn.settings.destination.get(
            name='HbEZ-destination')
        self.assertEqual(ds.email, {'id': '*****@*****.**'})

    def test_get_report(self):
        rs = self.conn.settings.report.get(name="HbEZ-report")
        self.assertEqual(rs.format, 'html')

    def test_get_retention_policy(self):
        rp = self.conn.settings.retention_policy.get(
            'HbEZ-testing')
        self.assertEqual(rp.retention_policy_name, "HbEZ-testing")

    def test_get_reports(self):
        rs = self.conn.settings.report.get()
        self.assertGreater(len(rs), 0)

    def test_get_notifications(self):
        ns = self.conn.settings.notification.get()
        self.assertGreater(len(ns), 0)

    def test_get_schedulers(self):
        sc = self.conn.settings.scheduler.get()
        self.assertGreater(len(sc), 0)

    def test_get_destinations(self):
        des = self.conn.settings.destination.get()
        self.assertGreater(len(des), 0)

    def test_get_reports(self):
        rep = self.conn.settings.report.get()
        self.assertGreater(len(rep), 0)

    def test_get_retention_policies(self):
        rp = self.conn.settings.retention_policy.get()
        self.assertGreater(len(rp), 0)

    def test_delete_notification(self):
        ret = self.conn.settings.notification.delete(
            notification_name='HbEZ-notification')
        self.assertTrue(ret)
        self.assertEqual(self.mock_request().mock_calls[2][0],
                         'delete')

    def test_delete_scheduler(self):
        ret = self.conn.settings.scheduler.delete(
            name='HbEZ-schedule')
        self.assertTrue(ret)
        self.assertEqual(self.mock_request().mock_calls[2][0],
                         'delete')

    def test_delete_destinaton(self):
        ret = self.conn.settings.destination.delete(
            name='HbEZ-destination')
        self.assertTrue(ret)
        self.assertEqual(self.mock_request().mock_calls[2][0],
                         'delete')

    def test_delete_report(self):
        ret = self.conn.settings.report.delete(name="HbEZ-report")
        self.assertTrue(ret)
        self.assertEqual(self.mock_request().mock_calls[2][0],
                         'delete')

    def test_delete_retention_policy(self):
        ret = self.conn.settings.retention_policy.delete(
            "HbEZ-testing")
        self.assertTrue(ret)
        self.assertEqual(self.mock_request().mock_calls[2][0],
                         'delete')

    def test_update_notification(self):
        ns = self.conn.settings.notification.get(
            notification_name='HbEZ-notification')
        from jnpr.healthbot import NotificationSchemaHttppost
        ns.http_post = NotificationSchemaHttppost(url='https://juniper.net')
        self.conn.settings.notification.update(ns)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['http-post']['url'],
            'https://juniper.net')

    def test_update_scheduler(self):
        sc = self.conn.settings.scheduler.get(name='HbEZ-schedule')
        sc.repeat = {'every': 'daily'}
        self.conn.settings.scheduler.update(sc)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['repeat']['every'],
            'daily')

    def test_update_destination(self):
        ds = self.conn.settings.destination.get(
            name='HbEZ-destination')
        ds.email = {'id': '*****@*****.**'}
        self.conn.settings.destination.update(ds)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['email']['id'],
            '*****@*****.**')

    def test_update_report(self):
        rs = self.conn.settings.report.get(name="HbEZ-report")
        rs.format = 'json'
        self.conn.settings.report.update(rs)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['format'],
            'json')

    def test_update_retention_policy(self):
        rp = self.conn.settings.retention_policy.get(
            'HbEZ-testing')
        rp.duration = '10h'
        self.conn.settings.retention_policy.update(rp)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['duration'],
            '10h')

    def test_license_get(self):
        ret = self.conn.settings.license.get(
            'xxx-xx-xxx')
        self.assertEqual(ret["customer-id"], "xxxx")

    def test_license_get_ids(self):
        ret = self.conn.settings.license.get_ids()
        self.assertEqual(ret, ['xxx-xx-xxx', 'yyy-yy-yyy'])

    def test_license_get_features(self):
        ret = self.conn.settings.license.get_features()
        self.assertEqual(ret.feature_description, "Max G8")

    def test_license_get_all(self):
        ret = self.conn.settings.license.get()
        self.assertEqual(ret[0].validity_type, "countdown")

    def test_license_delete(self):
        self.assertTrue(self.conn.settings.license.delete("xxx-xx-xxx"))

    def _mock_manager(self, *args, **kwargs):
        class MockResponse(Response):
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            @property
            def text(self):
                return 'did you just hit an error'

            def json(self):
                return self.json_data

            def to_dict(self):
                return self.json_data

            def raise_for_status(self):
                return None

        if args[0] == 'https://1.1.1.1:8080/api/v2/config/notification/HbEZ-notification/?working=true':
            return MockResponse({
                "description": "example of adding notification via API",
                "notification-name": "HbEZ-notification",
                "slack": {
                    "channel": "HbEZ",
                    "url": "http://testing"
                }
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/system-settings/scheduler/HbEZ-schedule/?working=true':
            return MockResponse({
                "name": "HbEZ-schedule",
                "repeat": {
                    "every": "week"
                },
                "start-time": "2019-07-22T05:32:23Z"
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/system-settings/report-generation/destination/HbEZ-destination/?working=true':
            return MockResponse({
                "email": {
                    "id": "*****@*****.**"
                },
                "name": "HbEZ-destination"
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/system-settings/report-generation/report/HbEZ-report/?working=true':
            return MockResponse({
                "destination": [
                    "HbEZ-destination"
                ],
                "format": "html",
                "name": "HbEZ-report",
                "schedule": [
                    "HbEZ-schedule"
                ]
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/system-settings/report-generation/reports/?working=true':
            return MockResponse({
                "report": [
                    {
                        "destination": [
                            "HbEZ-destination"
                        ],
                        "format": "html",
                        "name": "HbEZ-report",
                        "schedule": [
                            "HbEZ-schedule"
                        ]
                    }
                ]
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/notifications/?working=true':
            return MockResponse({
                "notification": [
                    {
                        "description": "example of adding notification via API",
                        "notification-name": "HbEZ-notification",
                        "slack": {
                            "channel": "HbEZ",
                            "url": "http://testing"
                        }
                    }
                ]
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/system-settings/schedulers/?working=true':
            return MockResponse({
                "scheduler": [
                    {
                        "name": "HbEZ-schedule",
                        "repeat": {
                            "every": "week"
                        },
                        "start-time": "2019-07-22T05:32:23Z"
                    }
                ]
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/system-settings/report-generation/destinations/?working=true':
            return MockResponse({
                "destination": [
                    {
                        "email": {
                            "id": "*****@*****.**"
                        },
                        "name": "HbEZ-destination"
                    }
                ]
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/retention-policy/HbEZ-testing/?working=true':
            return MockResponse({
                "retention-policy-name": "HbEZ-testing"
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/retention-policies/?working=true':
            return MockResponse({
                "retention-policy": [
                    {
                        "retention-policy-name": "HbEZ-testing"
                    }
                ]
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/notification/error/?working=true':
            obj = MockResponse(None, 404)

            def fn():
                raise ValueError
            obj.raise_for_status = fn
            return obj
        elif args[0] == '/license/key/{license_id}/contents/' and \
                args[2] == {'license_id': 'xxx-xx-xxx'}:
            return {"customer-id": "xxxx",
                    "end-date": "2106-02-0xxx",
                    "features": [{"capacity-flag": False,
                                  "capacity-value": 1,
                                  "feature-description": "Allow a..",
                                  "feature-id": 10001,
                                  "feature-name": "xxxx"},
                                 ],
                    "license-id": "xxx-xx-xxx",
                    "mode": "standalone",
                    "order-type": "commercial",
                    "sku-name": "HBxxx",
                    "start-date": "20xxx",
                    "sw-serial-id": "07xxx",
                    "validity-type": "xxx",
                    "version": 1}
        elif args[0] == '/license/keys/contents/':
            from jnpr.healthbot import LicenseKeySchema
            from jnpr.healthbot import LicenseKeysSchema
            return LicenseKeysSchema([LicenseKeySchema(**{"customer_id": "xxxx",
                    "end_date": "2106-02-0xxx",
                    "features": [{"capacity_flag": False,
                                  "capacity_value": 1,
                                  "feature_description": "Allow a..",
                                  "feature_id": 10001,
                                  "feature_name": "xxxx"},
                                 ],
                    "license_id": "xxx-xx-xxx",
                    "mode": "standalone",
                    "order_type": "commercial",
                    "sku_name": "HBxxx",
                    "start_date": "20xxx",
                    "sw_serial_id": "07xxx",
                    "validity_type": "countdown",
                    "version": 1})])
        elif args[0] == '/license/keys/':
            return ["xxx-xx-xxx", "yyy-yy-yyy"]
        elif args[0] == '/license/status/':
            from jnpr.healthbot import LicenseFeaturesSchema
            from jnpr.healthbot import LicenseFeatureSchema
            return LicenseFeaturesSchema(license_feature= LicenseFeatureSchema(**{'compliance': True,
                     'end_date': 111,
                     'feature_description': 'Max G8',
                     'feature_id': 111,
                     'feature_name': 'xxxx',
                     'license_remaining': 1,
                     'license_requested': 1,
                     'license_total': 1,
                     'license_usage': 1,
                     'max_remaining_days': 1,
                     'mode': 'standalone',
                     'valid_until': 'xxxx',
                     'validity_type': 'countdown'}))
        elif args[0] == '/license/key/{license_id}/' and args[1] == 'DELETE' and\
                args[2] == {'license_id': 'xxx-xx-xxx'}:
            return None
        return MockResponse(None, 404)
コード例 #12
0
class TestHealthBotClient(unittest.TestCase):

    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch('jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login')
    def setUp(self, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        self.mock_request = mock_request
        with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                   new_callable=PropertyMock) as mock_ver:
            with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                       new_callable=PropertyMock) as mock_cnf:
                with patch('jnpr.healthbot.healthbot.HealthBotClient.tenant',
                           new_callable=PropertyMock) as mock_tenant:

                    mock_ver.return_value = '4.0.0'
                    mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
                    mock_tenant.return_value = "default"
                    self.conn = HealthBotClient(
                        server='1.1.1.1',
                        user='******',
                        password='******').open()

    def test_check_attributes(self):
        self.assertIsInstance(self.conn.device, Device)
        self.assertIsInstance(self.conn.playbook, Playbook)
        self.assertIsInstance(self.conn.rule, Rule)

    def test_check_mandatory_params(self):
        self.assertRaises(
            ValueError,
            HealthBotClient,
            server="",
            user='******',
            password='******')
        self.assertRaises(
            ValueError,
            HealthBotClient,
            server="1.1.1.1",
            user="",
            password='******')
        self.assertRaises(
            ValueError,
            HealthBotClient,
            server="1.1.1.1",
            user="******",
            password="")

    def test_version_new_versions(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.assertEqual(self.conn.version, '4.0.0')

    def test_version_old_versions(self):
        self.assertEqual(self.conn.version, "4.0.0")

    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch('jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login')
    @patch('jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_logout')
    def test_context_manager(self, mock_user_logout, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                   new_callable=PropertyMock) as mock_ver:
            with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                       new_callable=PropertyMock) as mock_cnf:
                mock_ver.return_value = '2.0.1'
                mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
                with HealthBotClient(server='1.1.1.1', user='******',
                                     password='******') as conn:
                    self.assertEqual(conn.version, '2.0.1')

    def test_rollback(self):
        self.conn.rollback()
        self.assertEqual(self.mock_request().mock_calls[2][0],
                         'delete')

    def test_commit(self):
        with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                   new_callable=PropertyMock) as mock_cnf:
            mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
            self.conn.commit()
            self.assertEqual(self.mock_request().mock_calls[2][0],
                             'post')
            self.assertEqual(self.mock_request().mock_calls[2][1],
                             ('https://1.1.1.1:8080/api/v2/config/configuration',))

    @patch('jnpr.healthbot.healthbot.Path.open')
    def test_upload_helper_file(self, mock_open):
        self.mock_request().post.side_effect = self._mock_manager
        self.assertTrue(self.conn.upload_helper_file('text.rule'))
        self.assertTrue(self.conn.upload_helper_file('text.playbook'))
        self.assertTrue(self.conn.upload_helper_file('text'))

    def test_get_health(self):
        self.mock_request().get.side_effect = self._mock_manager
        health = self.conn.health()
        self.assertEqual(health.network_health, {'HbEZ': 'gray'})

    def _mock_manager(self, *args, **kwargs):
        class MockResponse(Response):
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

            def to_dict(self):
                return self.json_data

            def raise_for_status(self):
                return None

        if 'url' in kwargs:
            if kwargs['url'] == 'https://1.1.1.1:8080/api/v2/config/files/helper-files/text':
                return MockResponse({}, 200)
            if kwargs['url'] == 'https://1.1.1.1:8080/api/v2/config/topics':
                return MockResponse({}, 200)
            if kwargs['url'] == 'https://1.1.1.1:8080/api/v2/config/playbooks':
                return MockResponse({}, 200)
        if args[0] == 'https://1.1.1.1:8080/api/v2/system-details':
            return MockResponse({
                "server-time": "2019-07-24T12:51:20Z",
                "version": "HealthBot 4.0.0"
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/system-details':
            return MockResponse({
                "server-time": "2019-07-24T12:51:20Z",
                "version": "HealthBot 4.0.0"
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/health':
            return MockResponse({
                "device-health": {
                    "EVO": {
                        "EVO_Core": "gray"
                    },
                    "avro": {
                        "edge": "gray",
                        "real": "gray"
                    },
                    "demo": {},
                    "node1": {
                        "QFabric": "gray"
                    },
                    "vmx": {
                        "Core": "gray"
                    }
                },
                "network-health": {
                    "HbEZ": "gray"
                }
            }, 200)
        return MockResponse(None, 404)
コード例 #13
0
class TestDevices(unittest.TestCase):

    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch('jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login')
    def setUp(self, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        self.mock_request = mock_request
        with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                   new_callable=PropertyMock) as mock_ver:
            with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                       new_callable=PropertyMock) as mock_cnf:
                mock_ver.return_value = '4.0.0'
                mock_cnf.return_value = "https://1.1.1.1:8080/api/v2/config"
                self.conn = HealthBotClient(
                    server='1.1.1.1',
                    user='******',
                    password='******').open()

    def tearDown(self) -> None:
        self.conn.close()

    def test_add_device(self):
        self.mock_request().post.side_effect = self._mock_manager
        ret = self.conn.device.add('core', 'user', 'password')
        self.assertTrue(ret)

    def test_add_device_existing(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.device.add(
            'vmx', '10.221.136.140', 'user', 'password')
        self.assertTrue(ret)

    def test_add_device_using_schema(self):

        self.mock_request().post.side_effect = self._mock_manager
        from jnpr.healthbot import DeviceSchema

        ds = DeviceSchema(
            device_id='core',
            host='10.221.136.140',
            authentication={
                "password": {
                    "password": "******",
                    "username": "******"}})
        ret = self.conn.device.add(schema=ds)
        self.assertTrue(ret)

    def test_get_device_ids_default_empty(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.device.get_ids()
        self.assertEqual(ret, [])

    def test_delete_device(self):
        self.mock_request().delete.side_effect = self._mock_manager
        ret = self.conn.device.delete(device_id='core')
        self.assertTrue(ret)

    def test_delete_device_force(self):
        self.mock_request().delete.side_effect = self._mock_manager
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.device.delete(device_id='core', force=True)
        self.assertTrue(ret)
        self.assertEqual(self.mock_request().mock_calls[2][0], 'get')
        self.assertEqual(self.mock_request().mock_calls[4][0], 'put')
        self.assertEqual(self.mock_request().mock_calls[2][1][0],
                         'https://1.1.1.1:8080/api/v2/config/device-groups')
        self.assertEqual(self.mock_request().mock_calls[4][1][0],
                         'https://1.1.1.1:8080/api/v2/config/device-group/edge')
        self.assertEqual(self.mock_request().mock_calls[4][2]['json'],
                         {'description': 'testing', 'device-group-name': 'edge',
                          'devices': ['demo'], 'native-gpb': {'ports': [22000]},
                          'notification': {}, 'playbooks': ['eventd-debug-collection',
                                                            'eventd-kpis-playbook'],
                          'reports': [], 'variable': []})

    def test_get_device(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.device.get(device_id='core')
        self.assertIsInstance(ret, DeviceSchema)

    def test_get_devices(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.device.get()
        self.assertGreater(len(ret), 0)

    def test_update_device(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.device.get(device_id='core')
        obj.description = 'test in progress'
        self.conn.device.update(schema=obj)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['description'],
            'test in progress')

    def test_get_device_facts(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.device.get_facts(device_id='core')
        self.assertIn('facts', obj)

    def test_get_devices_facts(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.device.get_facts()
        self.assertNotEqual(len(obj), 0)

    def test_add_device_group(self):
        dgs = DeviceGroupSchema(device_group_name="edge",
                                description="All devices on the edge",
                                devices=['xyz'])
        self.assertTrue(self.conn.device_group.add(dgs))

    def test_add_device_group_wrong_schema(self):
        dgs = DeviceSchema(
            device_id='core',
            host='10.221.136.140',
            authentication={
                "password": {
                    "password": "******",
                    "username": "******"}})
        self.assertRaises(SchemaError, self.conn.device_group.add, dgs)

    def test_delete_device_group(self):
        self.assertTrue(
            self.conn.device_group.delete(
                device_group_name="edge"))

    def test_delete_device_group_force(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.assertTrue(
            self.conn.device_group.delete(
                device_group_name="edge", force=True))

    def test_get_device_group(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.device_group.get('Core')
        self.assertEqual(ret.description, 'testing')

    def test_update_device_group(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.device_group.get('Core')
        obj.description = 'test in progress'
        self.conn.device_group.update(schema=obj)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['description'],
            'test in progress')

    def test_get_device_groups(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.device_group.get()
        self.assertNotEqual(len(obj), 0)

    def test_check_device_in_group(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.assertTrue(
            self.conn.device_group.check_device_in_group(
                'vmx', 'Core'))

    def test_add_device_in_group(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.assertTrue(
            self.conn.device_group.add_device_in_group(
                'test', 'Core'))
        self.assertEqual(
            self.mock_request().mock_calls[4][2]['json']['devices'], [
                'vmx', 'core', 'test'])

    def test_add_device_in_group_with_group_data_none(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.assertTrue(
            self.conn.device_group.add_device_in_group(
                'test', 'alpha'))
        self.assertEqual(
            self.mock_request().mock_calls[4][2]['json'],
            {'device-group-name': 'alpha', 'devices': ['test']})

    def test_add_network_group(self):
        self.mock_request().post.side_effect = self._mock_manager
        self.mock_request().get.side_effect = self._mock_manager
        from jnpr.healthbot.modules.devices import NetworkGroupSchema
        ngs = NetworkGroupSchema(network_group_name="HbEZ")
        ret = self.conn.network_group.add(schema=ngs)
        self.assertTrue(ret)

    def test_add_network_group_existing(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.assertTrue(
            self.conn.network_group.add(
                network_group_name="HbEZ"))

    def test_get_network_group(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.network_group.get(network_group_name="HbEZ")
        self.assertEqual(obj.description, "testing")

    def test_get_network_groups(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.network_group.get()
        self.assertGreater(len(ret), 0)

    def test_update_network_group(self):
        self.mock_request().get.side_effect = self._mock_manager
        obj = self.conn.network_group.get('HbEZ')
        obj.description = 'test in progress'
        self.conn.network_group.update(schema=obj)
        self.assertEqual(
            self.mock_request().mock_calls[3][2]['json']['description'],
            'test in progress')

    def test_delete_network_group(self):
        self.assertTrue(self.conn.network_group.delete(
            network_group_name="HbEZ"))

    def test_get_device_health(self):
        self.mock_request().get.side_effect = self._mock_manager
        health = self.conn.device.health('avro')
        self.assertEqual(health.color, 'red')

    def test_get_device_group_health(self):
        self.mock_request().get.side_effect = self._mock_manager
        health = self.conn.device_group.health('Core')
        self.assertEqual(health.color, 'yellow')

    def test_get_network_group_health(self):
        self.mock_request().get.side_effect = self._mock_manager
        health = self.conn.network_group.health('Core')
        self.assertEqual(health.color, 'yellow')

    def _mock_manager(self, *args, **kwargs):
        class MockResponse(Response):
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

            def to_dict(self):
                return self.json_data

            def raise_for_status(self):
                return None

        if args[0] == 'https://1.1.1.1:8080/api/v2/config/device/core' and kwargs != {}:
            return MockResponse({}, 200)
        elif args[0] in ['https://1.1.1.1:8080/api/v2/config/device-groups',
                         'https://1.1.1.1:8080/api/v2/config/device-groups/?working=true']:
            return MockResponse({
                "device-group": [
                    {
                        "description": "learning",
                        "device-group-name": "Core",
                        "devices": [
                            "vmx"
                        ],
                        "native-gpb": {
                            "ports": [
                                22000
                            ]
                        },
                        "notification": {},
                        "playbooks": [
                            "eventd-debug-collection",
                            "eventd-kpis-playbook"
                        ],
                        "reports": [],
                        "variable": []
                    },
                    {
                        "description": "All devices on the edge",
                        "device-group-name": "edge",
                        "devices": [
                            "demo",
                            "core"
                        ],
                        "notification": {},
                        "playbooks": [],
                        "reports": []
                    },
                    {
                        "device-group-name": "real",
                        "devices": [
                            "avro"
                        ],
                        "notification": {},
                        "playbooks": [
                            "online-fpc-playbook",
                            "phyport"
                        ],
                        "reports": [],
                        "variable": [
                            {
                                "@": {
                                    "changed-seconds": 1563348601
                                },
                                "instance-id": "ge-1-0-0",
                                "playbook": "phyport",
                                "rule": "external/interface-info",
                                "variable-value": [
                                    {
                                        "name": "interface_name",
                                        "value": "ge-1/0/0"
                                    }
                                ]
                            },
                            {
                                "@": {
                                    "changed-seconds": 1563348601
                                },
                                "instance-id": "ge-1-0-1",
                                "playbook": "phyport",
                                "rule": "external/interface-info",
                                "variable-value": [
                                    {
                                        "name": "interface_name",
                                        "value": "ge-1/0/1"
                                    }
                                ]
                            },
                            {
                                "@": {
                                    "changed-seconds": 1563348601
                                },
                                "instance-id": "xyz",
                                "playbook": "online-fpc-playbook",
                                "rule": "linecard.statistics/update-online-fpc"
                            }
                        ]
                    },
                    {
                        "description": "xyz",
                        "device-group-name": "QFabric",
                        "devices": [
                            "vmx"
                        ],
                        "notification": {},
                        "playbooks": [],
                        "reports": [],
                        "variable": []
                    }
                ]
            }, 200)
        elif args[0] in ['https://1.1.1.1:8080/api/v2/config/device-group/Core/?working=true',
                         'https://1.1.1.1:8080/api/v2/config/device-group/Core']:
            return MockResponse({
                "description": "testing",
                "device-group-name": "Core",
                "devices": [
                    "vmx",
                    "core"
                ],
                "native-gpb": {
                    "ports": [
                        22000
                    ]
                },
                "notification": {},
                "playbooks": [
                    "eventd-debug-collection",
                    "eventd-kpis-playbook"
                ],
                "reports": [],
                "variable": []
            }, 200)
        elif args[0] in ['https://1.1.1.1:8080/api/v2/config/device-group/edge/?working=true',
                         'https://1.1.1.1:8080/api/v2/config/device-group/edge']:
            return MockResponse({
                "description": "testing",
                "device-group-name": "edge",
                "devices": [
                    "vmx",
                    "core"
                ],
                "native-gpb": {
                    "ports": [
                        22000
                    ]
                },
                "notification": {},
                "playbooks": [
                    "eventd-debug-collection",
                    "eventd-kpis-playbook"
                ],
                "reports": [],
                "variable": []
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/device-group/QFabric':
            return MockResponse({}, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/device/core':
            return MockResponse({}, 204)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/device/core/?working=true':
            return MockResponse({
                "authentication": {
                    "password": {
                        "password": "******",
                        "username": "******"
                    }
                },
                "device-id": "vmx",
                "host": "10.221.136.140",
                "open-config": {
                    "port": 32767
                },
                "system-id": "testing",
                "variable": [],
                "vendor": {
                    "juniper": {
                        "operating-system": "junos"
                    }
                }
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/device/core/facts/?working=true':
            return MockResponse({"device-id": "core",
                                 "facts": {"fpc": [],
                                           "hostname": "R1_re0",
                                           "platform": "MX960",
                                           "platform-info": [{"name": "re0",
                                                              "platform": "MX960"}],
                                           "product": "MX",
                                           }},
                                200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/devices/facts/?working=true':
            return MockResponse([{"device-id": "core",
                                  "facts": {"fpc": [],
                                            "hostname": "R1_re0",
                                            "platform": "MX960",
                                            "platform-info": [{"name": "re0",
                                                               "platform": "MX960"}],
                                            "product": "MX",
                                            }}],
                                200)
        if args[0] == 'https://1.1.1.1:8080/api/v2/config/devices/?working=true':
            return MockResponse({"device": [
                {
                    "authentication": {
                        "password": {
                            "password": "******",
                            "username": "******"
                        }
                    },
                    "device-id": "vmx",
                    "host": "10.221.136.140",
                    "open-config": {
                        "port": 32767
                    },
                    "system-id": "testing",
                    "variable": [],
                    "vendor": {
                        "juniper": {
                            "operating-system": "junos"
                        }
                    }
                },
                {
                    "authentication": {
                        "password": {
                            "password": "******",
                            "username": "******"
                        }
                    },
                    "device-id": "avro",
                    "host": "10.209.14.109",
                    "open-config": {
                        "port": 32767
                    },
                    "vendor": {
                        "juniper": {
                            "operating-system": "junos"
                        }
                    }
                },
                {
                    "authentication": {
                        "password": {
                            "password": "******",
                            "username": "******"
                        }
                    },
                    "device-id": "node1",
                    "host": "node1",
                    "open-config": {
                        "port": 32767
                    },
                    "vendor": {
                        "juniper": {
                            "operating-system": "junos"
                        }
                    }
                },
                {
                    "authentication": {
                        "password": {
                            "password": "******",
                            "username": "******"
                        }
                    },
                    "device-id": "demo",
                    "host": "10.221.136.140",
                    "system-id": "Demo:HbEZ"
                }
            ]
            }, 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/network-group/HbEZ/?working=true':
            obj = MockResponse({'description': "testing",
                                'network-group-name': 'HbEZ',
                                'notification': {},
                                'playbooks': [],
                                'reports': [],
                                'variable': None}, 200)
            return obj
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/network-groups/?working=true':
            obj = MockResponse({
                "network-group": [
                    {
                        "network-group-name": "HbEZ",
                        "notification": {},
                        "playbooks": [],
                        "reports": []
                    }
                ]
            }, 200)
            return obj
        elif args[0] == 'https://1.1.1.1:8080/api/v2/config/services/device-group/':
            return MockResponse(["edge"], 200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/health-tree/avro':
            return MockResponse({'children': [{'children': [{'children': [{'children': [{'color': 'red',
                                                                                         'data': 'either is '
                                                                                         'down',
                                                                                         'name': 'check-status',
                                                                                         'timestamp': '2019-07-22T10:28:08Z'}],
                                                                           'color': 'red',
                                                                           'name': '_instance_id: ["ge-1-0-1", '
                                                                           '"ge-1-0-0"], '
                                                                           '_playbook_name: phyport, '
                                                                           'name: ge-1/0/1'},
                                                                          {'children': [{'color': 'red',
                                                                                         'data': 'either is '
                                                                                         'down',
                                                                                         'name': 'check-status',
                                                                                         'timestamp': '2019-07-22T10:28:08Z'}],
                                                                           'color': 'red',
                                                                           'name': '_instance_id: ["ge-1-0-1", '
                                                                           '"ge-1-0-0"], '
                                                                           '_playbook_name: phyport, '
                                                                           'name: ge-1/0/0'}],
                                                             'color': 'red',
                                                             'name': 'external'}],
                                               'color': 'red',
                                               'name': 'real'}],
                                 'color': 'red',
                                 'data': None,
                                 'name': 'avro',
                                 'timestamp': None},
                                200)
        elif args[0] in ['https://1.1.1.1:8080/api/v2/health-tree/device-group/Core',
                         'https://1.1.1.1:8080/api/v2/health-tree/Core']:
            return MockResponse({"children": [{"children": [{"children": [],
                                                             "name": "interface.statistics"},
                                                            {"children": [],
                                                             "name": "linecard.fpc"},
                                                            {"children": [],
                                                             "name": "linecard.ospf"},
                                                            {"children": [],
                                                             "name": "linecard.statistics"},
                                                            {"children": [],
                                                             "name": "system.statistics"}],
                                               "color": "yellow",
                                               "name": "vmx"}],
                                 "color": "yellow",
                                 "name": "Core"},
                                200)
        elif args[0] == 'https://1.1.1.1:8080/api/v2/health-tree/network-group/Core':
            return MockResponse({"children": [{"children": [{"children": [],
                                                             "name": "interface.statistics"},
                                                            {"children": [],
                                                             "name": "linecard.fpc"},
                                                            {"children": [],
                                                             "name": "linecard.ospf"},
                                                            {"children": [],
                                                             "name": "linecard.statistics"},
                                                            {"children": [],
                                                             "name": "system.statistics"}],
                                               "color": "yellow",
                                               "name": "vmx"}],
                                 "color": "yellow",
                                 "name": "Core"},
                                200)
        return MockResponse(None, 404)
コード例 #14
0
 def test_context_manager(self, mock_user_logout, mock_user_login, mock_request):
     self.mock_user_login = _mock_user_login
     with HealthBotClient(server='1.1.1.1', user='******', password='******') as conn:
         self.assertEqual(conn.version, '2.0.1')
コード例 #15
0
class TestProfiles(unittest.TestCase):
    @patch('jnpr.healthbot.healthbot.requests.Session')
    @patch(
        'jnpr.healthbot.swagger.api.authentication_api.AuthenticationApi.user_login'
    )
    def setUp(self, mock_user_login, mock_request):
        self.mock_user_login = _mock_user_login
        self.mock_request = mock_request
        with patch('jnpr.healthbot.healthbot.HealthBotClient.version',
                   new_callable=PropertyMock) as mock_ver:
            with patch('jnpr.healthbot.healthbot.HealthBotClient.config_url',
                       new_callable=PropertyMock) as mock_cnf:
                mock_ver.return_value = '2.1.0'
                mock_cnf.return_value = "https://1.1.1.1:8080/api/v1"
                self.conn = HealthBotClient(server='1.1.1.1',
                                            user='******',
                                            password='******').open()

    def tearDown(self) -> None:
        self.conn.close()

    def test_add_caprofile(self):
        ca_prof_schema = CaProfileSchema(certificate_authority_crt='abc.crt',
                                         name='hbez')
        self.assertTrue(
            self.conn.settings.security.ca_profile.add(ca_prof_schema))
        self.assertTrue(
            self.conn.settings.security.ca_profile.add(
                certificate_authority_crt='abc.crt', name='hbez'))

    def test_get_caprofile(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.profile.security.ca_profile.get()
        self.assertEqual(ret[0].certificate_authority_crt, "test.crt")
        ret = self.conn.profile.security.ca_profile.get("hbez")
        self.assertEqual(ret.certificate_authority_crt, "test.crt")

    def test_update_caprofile(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.profile.security.ca_profile.get("hbez")
        ret.certificate_authority_crt = "changed.crt"
        self.assertTrue(self.conn.profile.security.ca_profile.update(ret))
        self.assertTrue(
            self.conn.profile.security.ca_profile.update(
                certificate_authority_crt='changed.crt', name='hbez'))

    def test_delete_caprofile(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.conn.profile.security.ca_profile.delete("hbez")
        self.assertEqual(self.mock_request().mock_calls[2][0], 'delete')

    def test_add_local_certificate(self):
        local_cert_schema = LocalCertificateSchema(client_crt='abc.crt',
                                                   client_key='pqr.key',
                                                   name='hbez')
        self.assertTrue(
            self.conn.settings.security.local_certificate.add(
                local_cert_schema))
        self.assertTrue(
            self.conn.settings.security.local_certificate.add(
                client_crt='abc.crt', client_key='pqr.key', name='hbez'))

    def test_get_local_certificate(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.profile.security.local_certificate.get()
        self.assertEqual(ret[0].client_crt, "test.crt")
        ret = self.conn.profile.security.local_certificate.get("hbez")
        self.assertEqual(ret.client_crt, "test.crt")

    def test_update_local_certificate(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.profile.security.local_certificate.get("hbez")
        ret.client_crt = "changed.crt"
        self.assertTrue(
            self.conn.profile.security.local_certificate.update(ret))
        self.assertTrue(
            self.conn.profile.security.local_certificate.update(
                client_crt='changed.crt', client_key='pqr.key', name='hbez'))

    def test_delete_local_certificate(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.conn.profile.security.local_certificate.delete("hbez")
        self.assertEqual(self.mock_request().mock_calls[2][0], 'delete')

    def test_add_ssh_key_profile(self):
        ssh_key_prof_schema = SshKeyProfileSchema(
            name='hbez',
            ssh_private_key_file='abc.crt',
            ssh_private_key_passphrase='%$#@#')
        self.assertTrue(
            self.conn.settings.security.ssh_key_profile.add(
                ssh_key_prof_schema))
        self.assertTrue(
            self.conn.settings.security.ssh_key_profile.add(
                name='hbez',
                ssh_private_key_file='abc.crt',
                ssh_private_key_passphrase='%$#@#'))

    def test_get_ssh_key_profile(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.profile.security.ssh_key_profile.get()
        self.assertEqual(ret[0].ssh_private_key_file, "test.key")
        ret = self.conn.profile.security.ssh_key_profile.get("hbez")
        self.assertEqual(ret.ssh_private_key_file, "test.key")

    def test_update_ssh_key_profile(self):
        self.mock_request().get.side_effect = self._mock_manager
        ret = self.conn.profile.security.ssh_key_profile.get("hbez")
        ret.ssh_private_key_file = "changed.crt"
        self.assertTrue(self.conn.profile.security.ssh_key_profile.update(ret))
        self.assertTrue(
            self.conn.profile.security.ssh_key_profile.update(
                name='hbez',
                ssh_private_key_file='changed.crt',
                ssh_private_key_passphrase='%$#@#'))

    def test_delete_ssh_key_profile(self):
        self.mock_request().get.side_effect = self._mock_manager
        self.conn.profile.security.ssh_key_profile.delete("hbez")
        self.assertEqual(self.mock_request().mock_calls[2][0], 'delete')

    def _mock_manager(self, *args):
        class MockResponse(Response):
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            @property
            def text(self):
                return 'did you just hit an error'

            def json(self):
                return self.json_data

            def to_dict(self):
                return self.json_data

            def raise_for_status(self):
                return None

        if args[0] == 'https://1.1.1.1:8080/api/v1/profile/security/ca-profiles/?working=true':
            return MockResponse(
                {
                    "ca-profile": [{
                        "certificate-authority-crt": "test.crt",
                        "name": "hbez"
                    }]
                }, 200)
        elif args[
                0] == 'https://1.1.1.1:8080/api/v1/profile/security/ca-profile/hbez/?working=true':
            return MockResponse(
                {
                    "certificate-authority-crt": "test.crt",
                    "name": "hbez"
                }, 200)
        elif args[
                0] == 'https://1.1.1.1:8080/api/v1/profile/security/local-certificates/?working=true':
            return MockResponse(
                {
                    "local-certificate": [{
                        "client-crt": "test.crt",
                        "client-key": "test.key",
                        "name": "hbez"
                    }]
                }, 200)
        elif args[
                0] == 'https://1.1.1.1:8080/api/v1/profile/security/local-certificate/hbez/?working=true':
            return MockResponse(
                {
                    "client-crt": "test.crt",
                    "client-key": "test.key",
                    "name": "hbez"
                }, 200)
        elif args[
                0] == 'https://1.1.1.1:8080/api/v1/profile/security/ssh-key-profiles/?working=true':
            return MockResponse(
                {
                    "ssh-key-profile": [{
                        "name":
                        "hbez",
                        "ssh-private-key-file":
                        "test.key",
                        "ssh-private-key-passphrase":
                        "$9$AQhzt1heK87dsWLZUiHmP1RE"
                    }]
                }, 200)
        elif args[
                0] == 'https://1.1.1.1:8080/api/v1/profile/security/ssh-key-profile/hbez/?working=true':
            return MockResponse(
                {
                    "name": "hbez",
                    "ssh-private-key-file": "test.key",
                    "ssh-private-key-passphrase": "$9$AQhzt1heK87dsWLZUiHmP1RE"
                }, 200)
        elif args[
                0] == 'https://1.1.1.1:8080/api/v1/notification/error/?working=true':
            obj = MockResponse(None, 404)

            def fn():
                raise ValueError

            obj.raise_for_status = fn
            return obj
        return MockResponse(None, 404)