def test_alternative_domains(registry): """Make sure we can specify an alternative domain.""" payload = { 'jwt': 'big-token', 'username': '******' } manager = ConfigManager() manager.set('cloud:server', 'https://testcloud.com') with requests_mock.Mocker() as mocker: mocker.post('https://testcloud.com/api/v1/auth/login/', json=payload) link_cloud(manager, '*****@*****.**', 'password') assert registry.get_config('arch:cloud_user') == 'user1' assert registry.get_config('arch:cloud_token') == 'big-token' cloud = IOTileCloud() payload = { 'token': 'new-token' } with requests_mock.Mocker() as mocker: mocker.post('https://testcloud.com/api/v1/auth/api-jwt-refresh/', json=payload) cloud.refresh_token() assert registry.get_config('arch:cloud_token') == 'new-token'
def basic_cloud(mock_cloud_private_nossl): """A basic mock iotile.cloud initialized with default information. There is a single project with 5 devices that have ids 1-5 and a second inaccessible project with 1 device (id 6) in it. """ ComponentRegistry.SetBackingStore('memory') domain, cloud = mock_cloud_private_nossl reg = ComponentRegistry() reg.set_config('cloud:server', domain) reg.set_config('arch:cloud_token', 'JWT_USER') reg.set_config('arch:cloud_token_type', 'jwt') cloud.quick_add_user('*****@*****.**', 'test') proj_id, _proj_slug = cloud.quick_add_project() proj2_id, _proj_slug = cloud.quick_add_project() devs = [ cloud.quick_add_device(proj_id, x, streamers=[100, 200]) for x in range(1, 6) ] client = IOTileCloud() cloud.quick_add_device(proj2_id) cloud.quick_add_sg(slug="water-meter-v1-1-0", app_tag=123) cloud.quick_add_sg(slug="water-meter-v1-1-1", app_tag=124) cloud.quick_add_dt(slug="internaltestingtemplate-v0-1-0", os_tag=234) cloud.quick_add_dt(slug="internaltestingtemplate-v0-1-1", os_tag=235) yield client, proj_id, cloud
def link_cloud(self, username=None, password=None, device_id=None): """Create and store a token for interacting with the IOTile Cloud API. You will need to call link_cloud once for each virtualenv that you create and want to use with any api calls that touch iotile cloud. Note that this method is called on a ConfigManager instance If you do not pass your username or password it will be prompted from you securely on stdin. If you are logging in for a user, the token will expire periodically and you will have to relogin. If you pass a device_id, you can obtain a limited token for that device that will never expire, assuming you have access to that device. Args: username (string): Your iotile.cloud username. This is prompted from stdin if not provided. password (string): Your iotile.cloud password. This is prompted from stdin if not provided. device_id (int): Optional device id to obtain permanent credentials for a device. """ reg = ComponentRegistry() domain = self.get('cloud:server') if username is None: # Both python 2 and 3 require native strings to be passed into getpass prompt_str = "Please enter your IOTile.cloud email: " if sys.version_info.major < 3: prompt_str = prompt_str.encode('utf-8') username = input(prompt_str) if password is None: # Both python 2 and 3 require native strings to be passed into getpass prompt_str = "Please enter your IOTile.cloud password: "******"Could not login to iotile.cloud as user %s" % username) reg.set_config('arch:cloud_user', cloud.username) reg.set_config('arch:cloud_token', cloud.token) reg.set_config('arch:cloud_token_type', cloud.token_type) if device_id is not None: cloud = IOTileCloud() cloud.impersonate_device(device_id)
def run(self): cloud = IOTileCloud() info = cloud.device_info(self._uuid) if self._sensorgraph is not None: if info['sg'] != self._sensorgraph: if not self._overwrite: raise ArgumentError("Cloud has incorrect sensorgraph setting", \ cloud_sensorgraph=info['sg'], expect_sensorgraph=self._sensorgraph) else: print("--> Updating cloud sensorgraph from %s to %s" % \ (info['sg'], self._sensorgraph)) cloud.set_sensorgraph(self._uuid, self._sensorgraph, app_tag=self._expected_app_tag) if self._device_template is not None: if info['template'] != self._device_template: if not self._overwrite: raise ArgumentError("Cloud has incorrect device_template setting", \ cloud_device_template=info['template'], expect_device_template=self._device_template) else: print("--> Updating cloud device template from %s to %s" % \ (info['template'], self._device_template)) cloud.set_device_template(self._uuid, self._device_template, os_tag=self._expected_os_tag)
def test_get_fleet(): """Make sure we can get fleets.""" auth_payload = { 'jwt': 'big-token', 'username': '******' } test_payload = {"count":1, "next":"Null", "previous":"Null", "results":[{"device":"d--0000-0000-0000-0001","always_on":True,"is_access_point":False}]} expected = { "d--0000-0000-0000-0001":{ "always_on":True, "is_access_point":False} } manager = ConfigManager() with requests_mock.Mocker() as mocker: mocker.post('https://iotile.cloud/api/v1/auth/login/', json=auth_payload) link_cloud(manager, '*****@*****.**', 'password') cloud = IOTileCloud() mocker.get('https://iotile.cloud/api/v1/fleet/g--0000-0000-0001/devices/', json=test_payload) mocker.get('https://iotile.cloud/api/v1/fleet/g--0000-0000-0002/devices/', status_code=404) assert cloud.get_fleet(1) == expected with pytest.raises(ArgumentError): cloud.get_fleet(2) with pytest.raises(ArgumentError): cloud.get_fleet(pow(16,12) + 1)
def test_refresh(registry): """Make sure we can properly refresh our jwt token.""" payload = { 'token': 'new-token' } registry.set_config("arch:cloud_token", 'old-token') registry.set_config("arch:cloud_user", 'test_user') cloud = IOTileCloud() with requests_mock.Mocker() as mocker: mocker.post('https://iotile.cloud/api/v1/auth/api-jwt-refresh/', json=payload) cloud.refresh_token() assert registry.get_config('arch:cloud_token') == 'new-token'
def test_check_time(): """ Make sure we can check if the time is correct""" json_true = {'now': datetime.datetime.now(tzutc()).strftime('%a, %d %b %Y %X %Z')} json_false = {'now': 'Wed, 01 Sep 2010 17:30:32 GMT'} payload = { 'jwt': 'big-token', 'username': '******' } manager = ConfigManager() with requests_mock.Mocker() as mocker: mocker.post('https://iotile.cloud/api/v1/auth/login/', json=payload) link_cloud(manager, '*****@*****.**', 'password') cloud = IOTileCloud() mocker.get('https://iotile.cloud/api/v1/server/', json=json_true) assert cloud.check_time() == True mocker.get('https://iotile.cloud/api/v1/server/', json=json_false) assert cloud.check_time() == False
def test_get_whitelist(): """ Make sure we can retrieve the whitelist correctly """ with open('test/large_mock_answer.json') as lma: j = json.load(lma) test_payload = j['whitelist_test'] p1 = j['whitelist_g1'] p2 = j['whitelist_g2'] p3 = j['whitelist_g3'] expected = j['expected'] empty_whitelist_test = j['empty_whitelist_test'] p4 = j['whitelist_g4'] payload = { 'jwt': 'big-token', 'username': '******' } manager = ConfigManager() with requests_mock.Mocker() as mocker: mocker.post('https://iotile.cloud/api/v1/auth/login/', json=payload) link_cloud(manager, '*****@*****.**', 'password') cloud = IOTileCloud() mocker.get('https://iotile.cloud/api/v1/fleet/?device=d--0000-0000-0000-0001', status_code=404) with pytest.raises(ExternalError): cloud.get_whitelist(1) mocker.get('https://iotile.cloud/api/v1/fleet/?device=d--0000-0000-0000-0002', json={'results':[]}) with pytest.raises(ExternalError): cloud.get_whitelist(2) mocker.get('https://iotile.cloud/api/v1/fleet/?device=d--0000-0000-0000-01bd', json=test_payload) mocker.get('https://iotile.cloud/api/v1/fleet/g--0000-0000-0001/devices/', json=p1) mocker.get('https://iotile.cloud/api/v1/fleet/g--0000-0000-0002/devices/', json=p2) mocker.get('https://iotile.cloud/api/v1/fleet/g--0000-0000-0003/devices/', json=p3) assert cloud.get_whitelist(0x1bd) == expected mocker.get('https://iotile.cloud/api/v1/fleet/?device=d--0000-0000-0000-01bd', json=empty_whitelist_test) mocker.get('https://iotile.cloud/api/v1/fleet/g--0000-0000-0004/devices/', json=p4) with pytest.raises(ExternalError): cloud.get_whitelist(0x1bd)
def ota_cloud(mock_cloud_private_nossl): """A basic mock iotile.cloud initialized with default information. There is a single project with 5 devices that have ids 1-5 and a second inaccessible project with 1 device (id 6) in it. Also adds ota deployments with various tags to check tagging logic """ ComponentRegistry.SetBackingStore('memory') domain, cloud = mock_cloud_private_nossl reg = ComponentRegistry() reg.set_config('cloud:server', domain) reg.set_config('arch:cloud_token', 'JWT_USER') reg.set_config('arch:cloud_token_type', 'jwt') cloud.quick_add_user('*****@*****.**', 'test') proj_id, _proj_slug = cloud.quick_add_project() proj2_id, _proj_slug = cloud.quick_add_project() devs = [ cloud.quick_add_device(proj_id, x, streamers=[100, 200]) for x in range(1, 7) ] ota_devs = [cloud.quick_add_ota_device_info(x) for x in range(1, 7)] client = IOTileCloud() cloud.quick_add_device(proj2_id) cloud.quick_add_sg(slug="water-meter-v1-1-0", app_tag=123) cloud.quick_add_sg(slug="water-meter-v1-1-1", app_tag=124) cloud.quick_add_dt(slug="internaltestingtemplate-v0-1-0", os_tag=234) cloud.quick_add_dt(slug="internaltestingtemplate-v0-1-1", os_tag=235) # Need to create a fleet to start OTA cloud.quick_add_fleet(devices=[1, 2], fleet_slug=1) cloud.quick_add_fleet(devices=[4, 5], fleet_slug=2) cloud.quick_add_fleet(devices=[1, 2, 4, 5, 6], fleet_slug=3) cloud.quick_add_fleet(devices=[1, 3, 4, 6], fleet_slug=4) # should always try to deploy from fleet 1 or 2 first, since they were added to the list first # even though release date is the same, order added takes precedence in this case criteria_eq = [ 'os_tag:eq:234', 'app_tag:eq:123', 'os_version:eq:0.0.2', 'app_version:eq:0.0.2' ] criteria_gt = [ 'os_tag:eq:233', 'app_tag:eq:122', 'os_version:gt:0.0.2', 'app_version:gteq:0.0.2' ] criteria_lt = [ 'os_tag:eq:235', 'app_tag:eq:124', 'os_version:lt:0.0.2', 'app_version:lteq:0.0.2' ] cloud.quick_add_deployment_to_fleet(fleet_id=1, deployment_id=1, criteria=criteria_eq) cloud.quick_add_deployment_to_fleet(fleet_id=2, deployment_id=2, criteria=criteria_gt) cloud.quick_add_deployment_to_fleet(fleet_id=3, deployment_id=3, criteria=criteria_lt) cloud.quick_add_deployment_to_fleet(fleet_id=4, deployment_id=4, criteria=criteria_lt, completed=True) yield client, proj_id, cloud