示例#1
0
 def __init__(self, service, http_client=None):
     """Create an OpenAPI client."""
     server_url, spec_file = OPENAPI_SPECS[service]
     json_spec = self._get_spec(spec_file)
     current_instance = BaseAPIClient._bravado_client_instance
     # We reinstantiate the bravado client instance if
     # 1. The current instance doesn't exist, or
     # 2. We're passing an http client (likely a mock), or
     # 3. The current instance is a Mock, meaning that either we want to
     #    use the `RequestClient` or we're passing a different mock.
     if (
         current_instance is None
         or http_client
         or isinstance(current_instance.swagger_spec.http_client, Mock)
     ):
         BaseAPIClient._bravado_client_instance = SwaggerClient.from_spec(
             json_spec,
             http_client=http_client or RequestsClient(ssl_verify=False),
             config={"also_return_response": True},
         )
     self._load_config_from_env()
     self._client = BaseAPIClient._bravado_client_instance
     if server_url is None:
         raise MissingAPIClientConfiguration(
             "Configuration to connect to {} is missing.".format(service)
         )
     self._client.swagger_spec.api_url = server_url
     self.server_url = server_url
示例#2
0
    def setup_swagger(self):
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        self.client = SwaggerClient.from_spec(load_file(self.spec),
                                              config=self.config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = self.api_url
示例#3
0
    def client(self):
        if getattr(self, '_client', None) is None:
            http_client = RequestsClient()
    
            netloc = urlparse(self.leader).netloc
            logger.debug("using bearer token for %s : %s", netloc, self.token)

            http_client.set_api_key(
                             netloc, "Bearer "+ self.token,
                             param_name='Authorization', param_in='header'
                            )

            self._client = SwaggerClient.from_url(
                        self.leader.strip("/")+"/apispec_1.json",
                        config={'use_models': False},
                        http_client=http_client,
                    )
        return self._client
示例#4
0
    def setup_swagger(self):
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        spec = pytest.config.getoption(self.spec_option)
        self.client = SwaggerClient.from_spec(load_file(spec),
                                              config=self.config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = self.make_api_url()
示例#5
0
    def setup(self):
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        self.client = SwaggerClient.from_spec(load_file('management_api.yml'),
                                              config=self.config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = "http://%s/api/%s/" % (
            pytest.config.getoption("host"), pytest.config.getoption("api"))
示例#6
0
    def setup(self):
        self.log = logging.getLogger("client.Client")
        self.api_url = API_URL
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        spec = pytest.config.getoption("spec")
        self.client = SwaggerClient.from_spec(load_file(spec),
                                              config=self.config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = self.api_url
示例#7
0
    def setup_swagger(self):
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        spec = pytest.config.getoption(self.spec_option)
        self.client = SwaggerClient.from_spec(load_file(spec),
                                              config=self.config,
                                              http_client=self.http_client)

        self.client.swagger_spec.api_url = "http://{}/api/{}/".format(pytest.config.getoption("host"),
                                                                      pytest.config.getoption("api"))
示例#8
0
 def __init__(self, service, http_client=None):
     """Create an OpenAPI client."""
     self._load_config_from_env()
     server_url, spec_file = OPENAPI_SPECS[service]
     json_spec = self._get_spec(spec_file)
     self._client = SwaggerClient.from_spec(
         json_spec,
         http_client=http_client or RequestsClient(ssl_verify=False),
         config={'also_return_response': True})
     if server_url is None:
         raise MissingAPIClientConfiguration(
             'Configuration to connect to {} is missing.'.format(service))
     self._client.swagger_spec.api_url = server_url
     self.server_url = server_url
示例#9
0
    def setup_swagger(self, host, swagger_spec):
        config = {
            "also_return_response": True,
            "validate_responses": True,
            "validate_requests": False,
            "validate_swagger_spec": False,
            "use_models": True,
        }

        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        self.client = SwaggerClient.from_spec(load_file(swagger_spec),
                                              config=config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = self.api_url
示例#10
0
class ManagementClient:
    config = {
        "also_return_response": True,
        "validate_responses": False,
        "validate_requests": False,
        "validate_swagger_spec": True,
        "use_models": True,
    }

    http_client = RequestsClient()
    http_client.session.verify = False

    client = SwaggerClient.from_spec(
        load_file(pytest.config.getoption("--management-spec")),
        config=config,
        http_client=http_client,
    )
    client.swagger_spec.api_url = "http://%s/api/%s" % (
        pytest.config.getoption("host"),
        pytest.config.getoption("api"),
    )

    group = client.get_model("Group")
    inventoryAttribute = client.get_model("Attribute")

    log = logging.getLogger("Client")

    def deleteAllGroups(self):
        groups = self.client.Management_API.List_Groups().result()[0]
        for g in groups:
            for d in self.getGroupDevices(g):
                self.deleteDeviceInGroup(g, d)

    def getAllDevices(self,
                      page=1,
                      sort=None,
                      has_group=None,
                      JWT="foo.bar.baz"):
        if not JWT.startswith("Bearer "):
            JWT = "Bearer " + JWT
        r, h = self.client.Management_API.List_Device_Inventories(
            page=page, sort=sort, has_group=has_group,
            Authorization=JWT).result()
        for i in parse_header_links(h.headers["link"]):
            if i["rel"] == "next":
                page = int(
                    dict(urlparse.parse_qs(urlparse.urlsplit(
                        i["url"]).query))["page"][0])
                return r + self.getAllDevices(page=page, sort=sort)
        else:
            return r

    def getDevice(self, device_id, Authorization="foo"):
        if not Authorization.startswith("Bearer "):
            Authorization = "Bearer " + Authorization
        r, _ = self.client.Management_API.Get_Device_Inventory(
            id=device_id, Authorization=Authorization).result()
        return r

    def getAllGroups(self):
        r, _ = self.client.Management_API.List_Groups().result()
        return r

    def getGroupDevices(self, group, expected_error=False):
        try:
            r = self.client.Management_API.Get_Devices_in_Group(
                name=group, Authorization=False).result()
        except Exception as e:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r[0]

    def deleteDeviceInGroup(self, group, device, expected_error=False):
        try:
            r = self.client.Management_API.Clear_Group(
                id=device, name=group, Authorization=False).result()
        except Exception:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r

    def addDeviceToGroup(self,
                         group,
                         device,
                         expected_error=False,
                         JWT="foo.bar.baz"):
        if not JWT.startswith("Bearer "):
            JWT = "Bearer " + JWT
        try:
            r = self.client.Management_API.Assign_Group(
                group=group, id=device, Authorization=JWT).result()
        except Exception:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r
示例#11
0
class Client(object):
    config = {
        'also_return_response': True,
        'validate_responses': False,
        'validate_requests': False,
        'validate_swagger_spec': True,
        'use_models': True,
    }

    http_client = RequestsClient()
    http_client.session.verify = False

    client = SwaggerClient.from_spec(load_file('management_api.yml'),
                                     config=config,
                                     http_client=http_client)
    client.swagger_spec.api_url = "http://%s/api/%s" % (
        pytest.config.getoption("host"), pytest.config.getoption("api"))

    group = client.get_model("Group")
    deviceNew = client.get_model("DeviceNew")
    inventoryAttribute = client.get_model("Attribute")

    def getInventoryListFromFile(self, filename="inventory_items"):
        attributeList = []

        with open(filename) as inf:
            r = csv.reader(inf)
            for row in r:
                n, v, d = row[0], row[1], row[2] if len(row) == 3 else None
                # does it matter if you pass a field name = None?
                attributeList.append(
                    self.inventoryAttribute(name=n, value=v, description=d))

        return attributeList

    def createDevice(self,
                     attributes,
                     deviceid=None,
                     description="test device"):
        if not deviceid:
            deviceid = "".join([format(i, "02x") for i in os.urandom(128)])

        deviceNew = self.deviceNew(id=deviceid,
                                   description=description,
                                   attributes=attributes)
        r, h = self.client.devices.post_devices(device=deviceNew,
                                                Authorization="foo").result()
        return deviceid

    def deleteAllGroups(self):
        groups = self.client.groups.get_groups().result()[0]
        for g in groups:
            for d in self.getGroupDevices(g):
                self.deleteDeviceInGroup(g, d)

    def getAllDevices(self, page=1, sort=None, has_group=None):
        r, h = self.client.devices.get_devices(page=page,
                                               sort=sort,
                                               has_group=has_group,
                                               Authorization="foo").result()
        for i in parse_header_links(h.headers["link"]):
            if i["rel"] == "next":
                page = int(
                    dict(urlparse.parse_qs(urlparse.urlsplit(
                        i["url"]).query))["page"][0])
                return r + self.getAllDevices(page=page, sort=sort)
        else:
            return r

    def getAllGroups(self):
        r, _ = self.client.groups.get_groups().result()
        return r

    def getGroupDevices(self, group, expected_error=False):
        try:
            r = self.client.groups.get_groups_name_devices(
                name=group, Authorization=False).result()
        except Exception as e:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r[0]

    def deleteDeviceInGroup(self, group, device, expected_error=False):
        try:
            r = self.client.devices.delete_devices_id_group_name(
                id=device, name=group, Authorization=False).result()
        except Exception:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r

    def addDeviceToGroup(self, group, device, expected_error=False):
        try:
            r = self.client.devices.put_devices_id_group(
                group=group, id=device, Authorization=False).result()
        except Exception:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r

    def verifyInventory(self, inventoryItems, expected_data=None):
        if isinstance(expected_data, str):
            expectedInventoryItems = self.getInventoryListFromFile(
                expected_data)
        elif isinstance(expected_data, dict):
            expectedInventoryItems = []
            for k in expected_data.keys():
                expectedInventoryItems.append(
                    self.inventoryAttribute(name=k, value=expected_data[k]))

        assert len(inventoryItems) == len(expected_data)

        for e in expected_data:
            if e not in inventoryItems:
                assert False, "Inventory data is incorrect"
示例#12
0
class ManagementClient:
    config = {
        'also_return_response': True,
        'validate_responses': False,
        'validate_requests': False,
        'validate_swagger_spec': True,
        'use_models': True,
    }

    http_client = RequestsClient()
    http_client.session.verify = False

    client = SwaggerClient.from_spec(load_file(
        pytest.config.getoption("--management-spec")),
                                     config=config,
                                     http_client=http_client)
    client.swagger_spec.api_url = "http://%s/api/%s" % (
        pytest.config.getoption("host"), pytest.config.getoption("api"))

    group = client.get_model("Group")
    deviceNew = client.get_model("DeviceNew")
    inventoryAttribute = client.get_model("Attribute")

    log = logging.getLogger('Client')

    def createDevice(self,
                     attributes,
                     deviceid=None,
                     description="test device"):
        if not deviceid:
            deviceid = "".join([format(i, "02x") for i in os.urandom(32)])

        deviceNew = self.deviceNew(id=deviceid,
                                   description=description,
                                   attributes=attributes)
        r, h = self.client.devices.post_devices(device=deviceNew,
                                                Authorization="foo").result()
        return deviceid

    def deleteAllGroups(self):
        groups = self.client.groups.get_groups().result()[0]
        for g in groups:
            for d in self.getGroupDevices(g):
                self.deleteDeviceInGroup(g, d)

    def getAllDevices(self, page=1, sort=None, has_group=None):
        r, h = self.client.devices.get_devices(page=page,
                                               sort=sort,
                                               has_group=has_group,
                                               Authorization="foo").result()
        for i in parse_header_links(h.headers["link"]):
            if i["rel"] == "next":
                page = int(
                    dict(urlparse.parse_qs(urlparse.urlsplit(
                        i["url"]).query))["page"][0])
                return r + self.getAllDevices(page=page, sort=sort)
        else:
            return r

    def getAllGroups(self):
        r, _ = self.client.groups.get_groups().result()
        return r

    def getGroupDevices(self, group, expected_error=False):
        try:
            r = self.client.groups.get_groups_name_devices(
                name=group, Authorization=False).result()
        except Exception as e:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r[0]

    def deleteDeviceInGroup(self, group, device, expected_error=False):
        try:
            r = self.client.devices.delete_devices_id_group_name(
                id=device, name=group, Authorization=False).result()
        except Exception:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r

    def addDeviceToGroup(self, group, device, expected_error=False):
        try:
            r = self.client.devices.put_devices_id_group(
                group=group, id=device, Authorization=False).result()
        except Exception:
            if expected_error:
                return []
            else:
                pytest.fail()

        else:
            return r