Esempio n. 1
0
class ProxyTestsBase(WirecloudTestCase, TestCase):

    fixtures = ('test_data.json', )
    tags = ('wirecloud-proxy', 'wirecloud-noselenium')
    populate = False
    use_search_indexes = False

    servers = {
        'http': {
            'example.com': DynamicWebServer(),
        },
    }

    @classmethod
    def setUpClass(cls):

        super(ProxyTestsBase, cls).setUpClass()
        cls.basic_url = reverse('wirecloud|proxy',
                                kwargs={
                                    'protocol': 'http',
                                    'domain': 'example.com',
                                    'path': '/path'
                                })
        cls.basic_referer = 'http://localhost/test/workspace'
        clear_cache()

    @classmethod
    def tearDownClass(cls):
        clear_cache()

        super(ProxyTestsBase, cls).tearDownClass()

    def setUp(self):
        self.network._servers['http']['example.com'].clear()
        cache.clear()
        self.client = Client()

        super(ProxyTestsBase, self).setUp()

    def read_response(self, response):

        if getattr(response, 'streaming', False) is True:
            return b"".join(response.streaming_content)
        else:
            return response.content

    def get_response_headers(self, response):
        headers = {}
        for header_name, header_value in response._headers.values():
            headers[header_name] = header_value
        return headers
Esempio n. 2
0
class ProxyTestsBase(WirecloudTestCase):

    fixtures = ('test_data.json', )
    tags = ('wirecloud-proxy', )

    servers = {
        'http': {
            'example.com': DynamicWebServer(),
        },
    }

    @classmethod
    def setUpClass(cls):

        super(ProxyTestsBase, cls).setUpClass()
        cls.basic_url = reverse('wirecloud|proxy',
                                kwargs={
                                    'protocol': 'http',
                                    'domain': 'example.com',
                                    'path': '/path'
                                })
        cls.OLD_WIRECLOUD_PLUGINS = getattr(settings, 'WIRECLOUD_PLUGINS',
                                            None)
        clear_cache()
        settings.WIRECLOUD_PLUGINS = ()

    @classmethod
    def tearDownClass(cls):
        settings.WIRECLOUD_PLUGINS = cls.OLD_WIRECLOUD_PLUGINS
        clear_cache()

        super(ProxyTestsBase, cls).tearDownClass()

    def setUp(self):
        self.network._servers['http']['example.com'].clear()
        cache.clear()

        super(ProxyTestsBase, self).setUp()

    def read_response(self, response):

        if getattr(response, 'streaming', False) is True:
            return b"".join(response.streaming_content)
        else:
            return response.content

    def get_response_headers(self, response):
        headers = {}
        for header_name, header_value in response._headers.values():
            headers[header_name] = header_value
        return headers
Esempio n. 3
0
class LocalCatalogueTestCase(WirecloudTestCase):

    fixtures = ('test_data', )
    servers = {
        'http': {
            'example.com': DynamicWebServer(),
        }
    }
    tags = ('wirecloud-localcatalogue', 'wirecloud-noselenium',
            'wirecloud-localcatalogue-noselenium')

    def setUp(self):
        super(LocalCatalogueTestCase, self).setUp()
        self.user = User.objects.get(username='******')
        self.user2 = User.objects.get(username='******')
        self.group = Group.objects.get(name='normusers')

    def read_file(self, *template):
        path = os.path.normpath(
            os.path.join(os.path.dirname(__file__), 'test-data', *template))
        with open(path, 'rb') as f:
            return f.read()

    def build_simple_wgt(self,
                         template_name,
                         html_content=None,
                         other_files=()):

        template = self.read_file(template_name)

        f = BytesIO()
        zf = zipfile.ZipFile(f, 'w')
        zf.writestr('config.xml', template)
        zf.writestr('test.html', html_content or BASIC_HTML_GADGET_CODE)
        zf.writestr('doc/', b'')  # TODO
        zf.writestr('images/catalogue.png', b'')
        zf.writestr('images/catalogue_smartphone.png', b'')
        for of in other_files:
            zf.writestr(of, b'')
        zf.close()
        return WgtFile(f)

    def check_basic_widget_info(self, resource):

        self.assertEqual(resource.vendor, 'Wirecloud')
        self.assertEqual(resource.short_name, 'test')
        self.assertEqual(resource.version, '0.1')
        self.assertEqual(resource.public, False)
        self.assertEqual(
            tuple(resource.users.values_list('username', flat=True)),
            ('test', ))
        self.assertEqual(tuple(resource.groups.values_list('name', flat=True)),
                         ())

        data = resource.get_processed_info(process_urls=False)
        self.assertEqual(data['vendor'], 'Wirecloud')
        self.assertEqual(data['name'], 'test')
        self.assertEqual(data['version'], '0.1')
        self.assertEqual(data['description'], 'Test Widget description')
        self.assertEqual(data['image'], 'images/catalogue.png')
        self.assertEqual(data['smartphoneimage'],
                         'images/catalogue_iphone.png')
        self.assertEqual(data['doc'], 'doc/index.html')
        self.assertEqual(data['license'], 'Apache License 2.0')
        self.assertEqual(data['licenseurl'],
                         'http://www.apache.org/licenses/LICENSE-2.0.html')

        self.assertEqual(len(data['properties']), 1)
        self.assertEqual(data['properties'], [{
            'default': '',
            'secure': False,
            'name': 'prop',
            'label': 'Property label',
            'type': 'text',
            'description': ''
        }])

        self.assertEqual(len(data['preferences']), 1)
        self.assertEqual(data['preferences'],
                         [{
                             'default': 'value',
                             'secure': False,
                             'name': 'pref',
                             'label': 'Preference label',
                             'type': 'list',
                             'options': [{
                                 'value': '1',
                                 'label': 'Option name'
                             }],
                             'readonly': False,
                             'description': 'Preference description',
                             'value': None
                         }])

        self.assertEqual(len(data['wiring']['inputs']), 1)
        self.assertEqual(data['wiring']['inputs'], [{
            'name': 'slot',
            'label': 'Slot label',
            'type': 'text',
            'description': '',
            'friendcode': 'test_friend_code',
            'actionlabel': ''
        }])

        self.assertEqual(len(data['wiring']['outputs']), 1)
        self.assertEqual(data['wiring']['outputs'],
                         [{
                             'name': 'event',
                             'label': 'Event label',
                             'type': 'text',
                             'description': '',
                             'friendcode': 'test_friend_code'
                         }])

    def test_widget_with_minimal_info(self):

        file_contents = self.build_simple_wgt('template9.xml')
        added, resource = install_resource_to_user(self.user,
                                                   file_contents=file_contents)

        self.assertTrue(added)
        resource_info = json.loads(resource.json_description)
        self.assertEqual(resource.vendor, 'Wirecloud')
        self.assertEqual(resource.short_name, 'test')
        self.assertEqual(resource.version, '0.1')
        self.assertEqual(resource_info['email'], '*****@*****.**')
        self.assertFalse(resource.public)
        self.assertEqual(
            tuple(resource.users.values_list('username', flat=True)),
            ('test', ))
        self.assertEqual(tuple(resource.groups.values_list('name', flat=True)),
                         ())

    def test_basic_widget_creation(self):

        file_contents = self.build_simple_wgt(
            'template1.xml',
            other_files=('images/catalogue.png', 'images/catalogue_iphone.png',
                         'doc/index.html'))
        added, resource = install_resource_to_user(self.user,
                                                   file_contents=file_contents)

        self.assertTrue(added)
        self.check_basic_widget_info(resource)

    def test_basic_widget_creation_from_rdf(self):

        file_contents = self.build_simple_wgt(
            'template1.rdf',
            other_files=('images/catalogue.png', 'images/catalogue_iphone.png',
                         'doc/index.html'))
        added, resource = install_resource_to_user(self.user,
                                                   file_contents=file_contents)

        self.assertTrue(added)
        self.check_basic_widget_info(resource)

    def test_basic_operator_creation_from_rdf(self):
        template = self.read_file('operatorTemplate1.rdf')
        parser = TemplateParser(template)
        data = parser.get_resource_info()

        self.assertEqual(data['vendor'], 'Wirecloud')
        self.assertEqual(data['name'], 'test operator')
        self.assertEqual(data['type'], 'operator')
        self.assertEqual(data['version'], '0.1')
        self.assertEqual(data['email'], '*****@*****.**')
        self.assertEqual(data['wiring']['inputs'][0]['label'], 'slot')
        self.assertEqual(data['wiring']['inputs'][0]['type'], 'text')
        self.assertEqual(data['wiring']['inputs'][0]['friendcode'],
                         'test_friend_code')
        self.assertEqual(data['wiring']['outputs'][0]['label'], 'event')
        self.assertEqual(data['wiring']['outputs'][0]['type'], 'text')
        self.assertEqual(data['wiring']['outputs'][0]['friendcode'],
                         'test_friend_code')
        self.assertEqual(data['preferences'][0]['label'], 'Preference label')
        self.assertEqual(data['preferences'][0]['description'],
                         'Preference description')
        self.assertEqual(data['preferences'][0]['default'], 'value')
        self.assertEqual(len(data['js_files']), 5)

        self.assertEqual(data['js_files'][0], '/examplecode1.js')
        self.assertEqual(data['js_files'][1], '/examplecode2.js')
        self.assertEqual(data['js_files'][2], '/examplecode3.js')
        self.assertEqual(data['js_files'][3], '/examplecode4.js')
        self.assertEqual(data['js_files'][4], '/examplecode5.js')

    def test_widget_deletion(self):
        resource = CatalogueResource.objects.get(vendor='Test',
                                                 short_name='Test Widget',
                                                 version='1.0.0')
        resource_pk = resource.pk
        xhtml_pk = resource.widget.xhtml.pk

        resource.delete()
        self.assertRaises(XHTML.DoesNotExist, XHTML.objects.get, pk=xhtml_pk)
        self.assertRaises(Widget.DoesNotExist,
                          Widget.objects.get,
                          resource__pk=resource_pk)
        self.assertRaises(CatalogueResource.DoesNotExist,
                          CatalogueResource.objects.get,
                          pk=resource_pk)

    def test_widget_code_cache(self):

        client = Client()
        client.login(username='******', password='******')
        widget_code_path = {
            'vendor': 'Wirecloud',
            'name': 'test',
            'version': '0.1',
            'file_path': 'index.html'
        }

        file_contents = self.build_simple_wgt(
            'template1.xml',
            other_files=('images/catalogue.png', 'images/catalogue_iphone.png',
                         'doc/index.html'))
        added, resource = install_resource_to_user(self.user,
                                                   file_contents=file_contents)
        self.assertTrue(added)
        resource_pk = resource.pk
        xhtml_pk = resource.widget.pk

        # Cache widget code
        response = client.get(
            reverse('wirecloud.showcase_media', kwargs=widget_code_path) +
            '?entrypoint=true')
        self.assertEqual(response.status_code, 200)
        old_code = response.content

        resource.delete()
        self.assertRaises(XHTML.DoesNotExist, XHTML.objects.get, pk=xhtml_pk)
        self.assertRaises(Widget.DoesNotExist,
                          Widget.objects.get,
                          resource__pk=resource_pk)
        self.assertRaises(CatalogueResource.DoesNotExist,
                          CatalogueResource.objects.get,
                          pk=resource_pk)

        # Use a different xhtml code
        file_contents = self.build_simple_wgt(
            'template1.xml',
            b'code',
            other_files=('images/catalogue.png', 'images/catalogue_iphone.png',
                         'doc/index.html'))
        resource = install_resource_to_user(self.user,
                                            file_contents=file_contents)

        response = client.get(
            reverse('wirecloud.showcase_media', kwargs=widget_code_path) +
            '?entrypoint=true')
        self.assertEqual(response.status_code, 200)
        new_code = response.content

        self.assertNotEqual(old_code, new_code)

    def test_install_resource_requires_wgt_instance(self):

        self.assertRaises(TypeError, install_resource, None, self.user)

    def test_install_resource_to_group(self):

        wgt_file = self.build_simple_wgt(
            'template1.xml',
            b'code',
            other_files=('images/catalogue.png', 'images/catalogue_iphone.png',
                         'doc/index.html'))

        added, resource = install_resource_to_group(self.group,
                                                    file_contents=wgt_file)
        self.assertTrue(added)
        self.assertTrue(resource.is_available_for(self.user))
        self.assertTrue(resource.is_available_for(self.user2))

    def test_add_m2m_race(self):

        # Check add_m2m handles race conditions
        field = Mock()
        field.filter().exists.side_effect = (False, True)
        field.add.side_effect = IntegrityError
        add_m2m(field, Mock())

    def test_add_m2m_integrity_exception(self):

        # Check add_m2m reraise not handled exceptions
        field = Mock()
        field.filter().exists.return_value = False
        field.add.side_effect = IntegrityError
        self.assertRaises(IntegrityError, add_m2m, field, Mock())

    def test_install_resource_to_group_duplicated(self):

        resource = CatalogueResource.objects.get(vendor='Test',
                                                 short_name='Test Widget',
                                                 version='1.0.0')
        resource.groups.add(self.group)

        wgt_file = self.build_simple_wgt('template10.xml', b'code')

        added, resource = install_resource_to_group(self.group,
                                                    file_contents=wgt_file)
        self.assertFalse(added)
        self.assertTrue(resource.is_available_for(self.user))
        self.assertTrue(resource.is_available_for(self.user2))

    def test_install_resource_to_all_users(self):

        wgt_file = self.build_simple_wgt(
            'template1.xml',
            b'code',
            other_files=('images/catalogue.png', 'images/catalogue_iphone.png',
                         'doc/index.html'))

        added, resource = install_resource_to_all_users(file_contents=wgt_file)
        self.assertTrue(added)
        self.assertTrue(resource.public)
        self.assertTrue(resource.is_available_for(self.user))
        self.assertTrue(resource.is_available_for(self.user2))

    def test_fix_dev_version(self):

        wgt_file = self.build_simple_wgt(
            'template11.xml',
            b'code',
            other_files=('images/catalogue.png', 'images/catalogue_iphone.png',
                         'doc/index.html'))
        original_template = wgt_file.get_template()
        original_version = TemplateParser(
            original_template).get_resource_info()['version']

        fix_dev_version(wgt_file, self.user)
        new_version = TemplateParser(
            wgt_file.get_template()).get_resource_info()['version']

        self.assertNotEqual(original_template, wgt_file.get_template())
        self.assertEqual(original_version + self.user.username, new_version)

    def test_install_resource_to_all_users_duplicated(self):

        CatalogueResource.objects.filter(vendor='Test',
                                         short_name='Test Widget',
                                         version='1.0.0').update(public=True)

        wgt_file = self.build_simple_wgt('template10.xml', b'code')

        added, resource = install_resource_to_all_users(file_contents=wgt_file)
        self.assertFalse(added)
        self.assertTrue(resource.public)
        self.assertTrue(resource.is_available_for(self.user))
        self.assertTrue(resource.is_available_for(self.user2))

    def test_widget_with_missing_translation_indexes(self):

        file_contents = self.build_simple_wgt('template3.xml')

        self.assertRaises(TemplateParseException, install_resource,
                          file_contents, self.user)
        self.assertRaises(CatalogueResource.DoesNotExist,
                          CatalogueResource.objects.get,
                          vendor='Wirecloud',
                          short_name='test',
                          version='0.1')

    def test_widget_with_notused_translation_indexes(self):

        file_contents = self.build_simple_wgt('template4.xml')

        self.assertRaises(TemplateParseException, install_resource,
                          file_contents, self.user)
        self.assertRaises(CatalogueResource.DoesNotExist,
                          CatalogueResource.objects.get,
                          vendor='Wirecloud',
                          short_name='test',
                          version='0.1')

    def test_template_translations(self):

        file_contents = self.build_simple_wgt(
            'template1.xml',
            other_files=('images/catalogue.png', 'images/catalogue_iphone.png',
                         'doc/index.html'))

        added, resource = install_resource_to_user(self.user,
                                                   file_contents=file_contents)

        self.assertTrue(added)
        self.changeLanguage('es')
        data = resource.get_processed_info(process_urls=False)
        self.assertEqual(data['vendor'], 'Wirecloud')
        self.assertEqual(data['name'], 'test')
        self.assertEqual(data['version'], '0.1')
        self.assertEqual(data['title'], 'Widget de prueba')
        self.assertEqual(data['description'],
                         'Descripción del Widget de pruebas')
        self.assertEqual(data['image'], 'images/catalogue.png')
        self.assertEqual(data['smartphoneimage'],
                         'images/catalogue_iphone.png')
        self.assertEqual(data['doc'], 'doc/index.html')

        self.assertEqual(len(data['properties']), 1)
        self.assertEqual(data['properties'], [{
            'default': '',
            'secure': False,
            'name': 'prop',
            'label': 'Etiqueta de la propiedad',
            'type': 'text',
            'description': ''
        }])

        self.assertEqual(len(data['preferences']), 1)
        self.assertEqual(
            data['preferences'],
            [{
                'default': 'value',
                'secure': False,
                'name': 'pref',
                'label': 'Etiqueta de la preferencia',
                'type': 'list',
                'options': [{
                    'value': '1',
                    'label': 'Nombre de la opción'
                }],
                'readonly': False,
                'description': 'Descripción de la preferencia',
                'value': None
            }])

        self.assertEqual(len(data['wiring']['inputs']), 1)
        self.assertEqual(data['wiring']['inputs'], [{
            'name': 'slot',
            'label': 'Etiqueta del endpoint de entrada',
            'type': 'text',
            'description': '',
            'friendcode': 'test_friend_code',
            'actionlabel': ''
        }])

        self.assertEqual(len(data['wiring']['outputs']), 1)
        self.assertEqual(data['wiring']['outputs'],
                         [{
                             'name': 'event',
                             'label': 'Etiqueta del endpoint de salida',
                             'type': 'text',
                             'description': '',
                             'friendcode': 'test_friend_code'
                         }])

    def test_repeated_translation_indexes(self):

        file_contents = self.build_simple_wgt('template2.xml')

        resource = install_resource(file_contents, self.user)

        data = resource.get_processed_info()
        self.assertEqual(data['title'], 'Test Widget')
        self.assertEqual(data['version'], '0.2')

        self.assertEqual(len(data['properties']), 1)
        self.assertEqual(data['properties'], [{
            'default': '',
            'secure': False,
            'name': 'prop',
            'label': 'Label',
            'type': 'text',
            'description': ''
        }])

        self.assertEqual(len(data['preferences']), 1)
        self.assertEqual(data['preferences'], [{
            'default': 'value',
            'secure': False,
            'name': 'pref',
            'label': 'Label',
            'readonly': False,
            'type': 'text',
            'description': 'Preference description',
            'value': None
        }])

        self.assertEqual(len(data['wiring']['inputs']), 1)
        self.assertEqual(data['wiring']['inputs'], [{
            'name': 'slot',
            'label': 'Label',
            'type': 'text',
            'description': '',
            'friendcode': 'test_friend_code',
            'actionlabel': ''
        }])

        self.assertEqual(len(data['wiring']['outputs']), 1)
        self.assertEqual(data['wiring']['outputs'],
                         [{
                             'name': 'event',
                             'label': 'Label',
                             'type': 'text',
                             'description': '',
                             'friendcode': 'test_friend_code'
                         }])

    def test_widgets_with_invalid_format(self):

        file_contents = self.build_simple_wgt('template5.xml')
        self.assertRaises(TemplateParseException, install_resource,
                          file_contents, self.user)
        self.assertRaises(CatalogueResource.DoesNotExist,
                          CatalogueResource.objects.get,
                          vendor='Wirecloud',
                          short_name='test',
                          version='0.1')

        file_contents = self.build_simple_wgt('template6.xml')
        self.assertRaises(TemplateParseException, install_resource,
                          file_contents, self.user)
        self.assertRaises(CatalogueResource.DoesNotExist,
                          CatalogueResource.objects.get,
                          vendor='Wirecloud',
                          short_name='test',
                          version='0.1')

        file_contents = self.build_simple_wgt('template7.xml')
        self.assertRaises(TemplateParseException, install_resource,
                          file_contents, self.user)
        self.assertRaises(CatalogueResource.DoesNotExist,
                          CatalogueResource.objects.get,
                          vendor='Wirecloud',
                          short_name='test',
                          version='0.1')

    def test_widget_with_unmet_requirements(self):

        file_contents = self.build_simple_wgt('template8.xml')

        self.assertRaises(Exception, install_resource, file_contents,
                          self.user)
        self.assertRaises(Widget.DoesNotExist,
                          Widget.objects.get,
                          resource__vendor='Example',
                          resource__short_name='test',
                          resource__version='0.1')

    def test_widget_with_unmet_requirements_rdf(self):

        file_contents = self.build_simple_wgt('template8.rdf')

        self.assertRaises(Exception, install_resource, file_contents,
                          self.user)
        self.assertRaises(Widget.DoesNotExist,
                          Widget.objects.get,
                          resource__vendor='Example',
                          resource__short_name='test',
                          resource__version='0.1')

    def test_widgets_with_invalid_format_rdf(self):

        file_contents = self.build_simple_wgt('template5.rdf')
        self.assertRaises(TemplateParseException, install_resource,
                          file_contents, self.user)

        file_contents = self.build_simple_wgt('template6.rdf')
        self.assertRaises(TemplateParseException, install_resource,
                          file_contents, self.user)

    def test_basic_mashup(self):

        file_contents = self.build_simple_wgt(
            os.path.join('..', '..', 'workspace', 'test-data', 'wt1.xml'))
        added, resource = install_resource_to_user(self.user,
                                                   file_contents=file_contents)

        self.assertTrue(added)
        self.assertEqual(resource.vendor, 'Wirecloud Test Suite')
        self.assertEqual(resource.short_name, 'Test Mashup')
        self.assertEqual(resource.version, '1')
        self.assertTrue(resource.is_available_for(self.user))

    def test_basic_mashup_rdf(self):

        file_contents = self.build_simple_wgt(
            os.path.join('..', '..', 'workspace', 'test-data', 'wt1.rdf'))
        added, resource = install_resource_to_user(self.user,
                                                   file_contents=file_contents)

        self.assertTrue(added)
        self.assertEqual(resource.vendor, 'Wirecloud Test Suite')
        self.assertEqual(resource.short_name, 'Test Mashup')
        self.assertEqual(resource.version, '1')
        self.assertTrue(resource.is_available_for(self.user))

    def test_mashup_with_missing_embedded_resources(self):

        file_contents = self.build_simple_wgt(
            'mashup_with_missing_embedded_resources.xml')
        self.assertRaises(InvalidContents,
                          install_resource_to_user,
                          self.user,
                          file_contents=file_contents)

    def test_mashup_with_invalid_embedded_resources(self):

        file_contents = WgtFile(
            BytesIO(
                self.read_file("..", "..", "..", "commons", "test-data",
                               "Wirecloud_mashup-with-invalid-macs_1.0.wgt")))
        try:
            install_resource_to_user(self.user, file_contents=file_contents)
            self.fail('InvalidContents exception not raised')
        except InvalidContents as e:
            self.assertIn('Invalid embedded file: ', e.message)
Esempio n. 4
0
class StoreTestCase(WirecloudTestCase):

    tags = ('wirecloud-fiware', 'wirecloud-fiware-store',
            'wirecloud-noselenium')
    servers = {
        'http': {
            'example.com': DynamicWebServer()
        },
    }

    def setUp(self):

        super(StoreTestCase, self).setUp()

        self.store_client = StoreClient('http://example.com')
        self.network._servers['http']['example.com'].clear()

    def read_response_file(self, *response):
        f = open(
            os.path.join(os.path.dirname(__file__), 'test-data', *response))
        contents = f.read()
        f.close()

        return contents

    def test_storeclient_complain_about_relative_urls(self):

        self.assertRaises(ValueError, StoreClient, 'path')
        self.assertRaises(ValueError, StoreClient, '/path')
        self.assertRaises(ValueError, StoreClient, '//store.example.com/path')

    def test_storeclient_handle_url_trailing_slashes(self):

        test_client = StoreClient('http://store.example.com')
        self.assertEqual(test_client._url, 'http://store.example.com/')

        test_client = StoreClient('http://store.example.com///')
        self.assertEqual(test_client._url, 'http://store.example.com/')

    def test_storeclient_must_ignore_params_query_and_framgent(self):

        test_client = StoreClient('http://store.example.com/?query=a#a')
        self.assertEqual(test_client._url, 'http://store.example.com/')

    def test_unexpected_response(self):

        response = Mock()
        response.status_code = 422
        response.text = '{"message": "Unprocessable Entity"}'
        exception = UnexpectedResponse(response)
        self.assertEqual(
            "%s" % exception,
            "Unexpected response from server (Error code: 422, Message: Unprocessable Entity)"
        )

    def test_unexpected_response_without_error_message(self):

        response = Mock()
        response.status_code = 422
        response.content = 'no processable response'
        exception = UnexpectedResponse(response)
        self.assertEqual("%s" % exception,
                         "Unexpected response from server (422 error code)")

    def test_get_supported_plugins(self):

        self.network._servers['http']['example.com'].add_response(
            'GET', '/api/offering/resources/plugins', {'content': '[]'})
        self.assertEqual(
            self.store_client.get_supported_plugins('wirecloud_token'), [])

    def test_get_supported_plugins_unexpected_response(self):

        self.network._servers['http']['example.com'].add_response(
            'GET', '/api/offering/resources/plugins', {
                'status_code': 409,
                'content': '{"message": "error description"}'
            })
        self.assertRaises(UnexpectedResponse,
                          self.store_client.get_supported_plugins,
                          'wirecloud_token')

    def test_offering_info_retreival(self):

        response_text = self.read_response_file('offering_info.json')
        response = json.loads(response_text)
        self.network._servers['http']['example.com'].add_response(
            'GET', '/api/offering/offerings/17', {'content': response_text})
        info = self.store_client.get_offering_info('17', 'wirecloud_token')

        self.assertEqual(info, response)

    def test_offering_info_retreival_404(self):

        self.assertRaises(NotFound, self.store_client.get_offering_info, '17',
                          'wirecloud_token')

    def test_offering_info_retreival_unexpected_response(self):

        self.network._servers['http']['example.com'].add_response(
            'GET', '/api/offering/offerings/17', {
                'status_code': 409,
                'content': '{"message": "error description"}'
            })
        self.assertRaises(UnexpectedResponse,
                          self.store_client.get_offering_info, '17',
                          'wirecloud_token')

    def test_start_purchase(self):

        self.network._servers['http']['example.com'].add_response(
            'POST', '/api/contracting/form', {
                'content':
                '{"url": "http://store.example.org/api/contracting/form?ID=54662b63b73e260d625844ed521b881bb73e2611f137206b"}'
            })
        result = self.store_client.start_purchase(
            OFFERING_URL, 'http://example.com/redirect_uri', 'wirecloud_token')
        self.assertIn('url', result)

    def test_start_purchase_not_found(self):

        self.assertRaises(NotFound, self.store_client.start_purchase,
                          OFFERING_URL, 'http://example.com/redirect_uri',
                          'wirecloud_token')

    def test_start_purchase_unexpected_response(self):

        self.network._servers['http']['example.com'].add_response(
            'POST', '/api/contracting/form', {
                'status_code': 500,
                'content': '{"message": "error description"}'
            })
        self.assertRaises(UnexpectedResponse, self.store_client.start_purchase,
                          OFFERING_URL, 'http://example.com/redirect_uri',
                          'wirecloud_token')

    def test_resource_download(self):

        resource_link = '/media/resources/CoNWeT__Kurento one2one widget__1.1.2__CoNWeT_kurento-one2one_1.1.2.wgt'
        self.network._servers['http']['example.com'].add_response(
            'GET', resource_link, {'content': 'resource content'})
        self.assertEqual(
            self.store_client.download_resource(resource_link,
                                                'wirecloud_token'),
            b'resource content')

    def test_resource_download_unexpected_response(self):

        resource_link = '/media/resources/CoNWeT__Kurento one2one widget__1.1.2__CoNWeT_kurento-one2one_1.1.2.wgt'
        self.network._servers['http']['example.com'].add_response(
            'GET', resource_link, {
                'status_code': 409,
                'content': '{"message": "error description"}'
            })
        self.assertRaises(UnexpectedResponse,
                          self.store_client.download_resource, resource_link,
                          'wirecloud_token')

    def test_resource_upload(self):

        self.network._servers['http']['example.com'].add_response(
            'POST', '/api/offering/resources', {
                'content': '',
                'status_code': 200
            })
        self.store_client.upload_resource(
            'Resource Name', '1.0', 'resource.zip',
            'Resource file, probably a widget, an operator or a mashup',
            'application/octet-stream', BytesIO(b'file contents'),
            'test_token')

    def test_resource_upload_resource_type(self):

        self.network._servers['http']['example.com'].add_response(
            'POST', '/api/offering/resources', {
                'content': '',
                'status_code': 200
            })
        self.store_client.upload_resource(
            'Resource Name',
            '1.0',
            'resource.zip',
            'Resource file, probably a widget, an operator or a mashup',
            'application/octet-stream',
            BytesIO(b'file contents'),
            'test_token',
            resource_type="Mashable application component")

    def test_resource_upload_conflict(self):

        self.network._servers['http']['example.com'].add_response(
            'POST', '/api/offering/resources', {
                'content': '',
                'status_code': 409
            })
        self.assertRaises(
            Conflict, self.store_client.upload_resource, 'Resource Name',
            '1.0', 'resource.zip',
            'Resource file, probably a widget, an operator or a mashup',
            'application/octet-stream', BytesIO(b'file contents'),
            'test_token')

    def test_resource_upload_error(self):

        self.network._servers['http']['example.com'].add_response(
            'POST', '/api/offering/resources', {
                'content': '',
                'status_code': 400
            })
        self.assertRaises(
            UnexpectedResponse, self.store_client.upload_resource,
            'Resource Name', '1.0', 'resource.zip',
            'Resource file, probably a widget, an operator or a mashup',
            'application/octet-stream', BytesIO(b'file contents'),
            'test_token')
Esempio n. 5
0
class BasicSeleniumGuideTests(WirecloudSeleniumTestCase):
    fixtures = ('initial_data', 'selenium_test_data', 'guide_test_data')
    servers = {
        'http': {
            'marketplace.example.com': DynamicWebServer(),
            'repository.example.com': LocalFileSystemServer(market_path_base('responses', 'repository')),
            'static.example.com': LocalFileSystemServer(market_path_base('responses', 'static')),
            'store.example.com': DynamicWebServer(fallback=LocalFileSystemServer(market_path_base('responses', 'store'))),
            'store2.example.com': DynamicWebServer(fallback=LocalFileSystemServer(market_path_base('responses', 'store2'))),
            'orion.lab.fiware.org:1026': RealWebServer()
        },
        'https': {
            'ngsiproxy.lab.fiware.org': RealWebServer()
        }
    }

    tags = ('wirecloud-guide',)

    @classmethod
    def setUpClass(cls):

        if not os.path.exists(os.path.join(settings.BASEDIR, USER_GUIDE_IMAGES_PATH)):
            os.makedirs(os.path.join(settings.BASEDIR, USER_GUIDE_IMAGES_PATH))

        WirecloudSeleniumTestCase.setUpClass.__func__(cls)

    def setUp(self):
        access_token = settings.GUIDEBUILDER_AUTH_ACCESS_TOKEN
        User.objects.get(username='******').social_auth.create(provider='fiware', uid='admin', extra_data={"access_token": access_token})
        components = ['TestOperator', 'test-mashup', 'Test', 'test-mashup-dependencies']
        for c in components:
            CatalogueResource.objects.get(short_name=c).delete()

        self.store_list_response = read_response_file(
            'responses', 'marketplace', 'store_list.xml')
        self.store1_offerings = read_response_file(
            'responses', 'marketplace', 'store1_offerings.xml')
        self.store2_offerings = read_response_file(
            'responses', 'marketplace', 'store2_offerings.xml')
        super(BasicSeleniumGuideTests, self).setUp()

        self.network._servers['http']['marketplace.example.com'].clear()
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/registration/stores/', {'content': self.store_list_response})
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/FIWARE%20Lab/offerings', {'content': self.store1_offerings})
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/FIWARE/offerings', {'content': self.store2_offerings})

    def configure_ngsi_source(self, source):
        popup = source.display_preferences()
        setts_btn = popup.get_entry("Settings")
        ActionChains(self.driver).move_to_element(setts_btn).perform()
        imgp = take_capture(self.driver, prepath="wiring", name='NGSISource_settings')
        box = create_box(popup.element, 40)
        box = (box[0] - 120, box[1], box[2], box[3])
        add_pointer(imgp, get_position(setts_btn, 0.8, 0.5), True)
        crop_image(imgp, *box)
        setts_btn.click()

        dialog = get_first_displayed(self.driver, '.window_menu')
        self.fill_form_input(dialog.find_element_by_css_selector('input[name="ngsi_server"]'),
                             'http://orion.lab.fiware.org:1026/')
        self.fill_form_input(dialog.find_element_by_css_selector('input[name="ngsi_proxy"]'),
                             'https://ngsiproxy.lab.fiware.org')
        self.fill_form_input(dialog.find_element_by_css_selector('input[name="ngsi_entities"]'),
                             'Node, AMMS, Regulator')
        self.fill_form_input(dialog.find_element_by_css_selector(
            'input[name="ngsi_update_attributes"]'), 'Latitud, Longitud, presence, batteryCharge, illuminance, ActivePower, ReactivePower, electricPotential, electricalCurrent')
        dialog.find_element_by_css_selector('.btn-primary').click()

    def configure_ngsi_entity(self, source):
        source.show_settings_modal()
        dialog = get_first_displayed(self.driver, '.window_menu')
        self.fill_form_input(dialog.find_element_by_css_selector('input[name="coordinates_attr"]'),
                             'Latitud, Longitud')
        dialog.find_element_by_css_selector('.btn-primary').click()

    @uses_extra_resources(list_resources)
    def test_creating_new_workspace(self):
        def take_capture(*args, **kargs):
            return midd_take_capture(*args, prepath="create_workspace", **kargs)

        # Intitialization
        self.driver.set_window_size(1024, 768)
        self.login()
        self.create_workspace('My Multimedia Workspace')
        self.create_workspace('Issue Trouble')
        self.open_menu().click_entry('Workspace')
        self.wait_wirecloud_ready()

        menu_widg = self.driver.find_element_by_css_selector(
            '.wirecloud_header_nav .icon-reorder')

        # Empty workspace screenshot
        imgp = take_capture(self.driver, extra=1)

        # Workspace list screenshot
        menu = self.open_menu()
        imgp = take_capture(self.driver, extra='workspace_menu')
        box = create_box(menu.element, 10)
        box = (box[0], box[1] - 40, box[2], box[3])
        add_pointer(imgp, get_position(menu_widg))  # Add the mouse
        crop_image(imgp, *box)

        # Capture new workspace
        newworkspace_menu = menu.get_entry('New workspace')
        ActionChains(self.driver).move_to_element(newworkspace_menu).perform()
        imgp = take_capture(self.driver, extra=4)
        add_pointer(imgp, get_position(newworkspace_menu, 0.8, 0.5))
        crop_down(imgp, menu.element)  # Crop down the image

        # Capture writing new workspace name
        newworkspace_menu.click()
        dialog = self.driver.find_element_by_css_selector(
            '.window_menu.new_workspace')
        self.fill_form_input(dialog.find_element_by_css_selector('input[name="name"]'),
                             'History Info')
        imgp = take_capture(self.driver, extra=5)
        crop_image(imgp, *create_box(dialog))

        # Wait complete and capture state
        # dialog.find_element_by_xpath("//*[text()='Accept']").click()
        dialog.find_element_by_css_selector(
            'button.btn-primary.se-btn').click()
        self.wait_wirecloud_ready()
        imgp = take_capture(self.driver, extra='HistoryInfoWorkspace')
        crop_down(
            imgp, self.driver.find_element_by_css_selector('.emptyWorkspaceInfoBox'))

        btn = self.driver.find_element_by_css_selector(
            '.wc-toolbar .icon-shopping-cart')
        ActionChains(self.driver).move_to_element(btn).perform()
        time.sleep(0.2)
        imgp = take_capture(self.driver, extra=17)
        add_pointer(imgp, get_position(btn, 0.8, 0.5))
        crop_down(
            imgp, self.driver.find_element_by_css_selector('.emptyWorkspaceInfoBox'))

        # Workspace Settings
        self.open_menu().click_entry('Settings')
        dialog = self.driver.find_element_by_css_selector(
            '.window_menu.workspace_preferences')
        imgp = take_capture(self.driver, extra='WorkspaceSettings')
        crop_image(imgp, *create_box(dialog))

    test_creating_new_workspace.tags = ('ui-new-workspace',)

    @uses_extra_resources(list_resources)
    def test_browsing_marketplace(self):
        def take_capture(*args, **kargs):
            return midd_take_capture(*args, prepath="browsing_marketplace", **kargs)

        self.driver.set_window_size(1024, 768)
        self.login()

        with self.marketplace_view as marketplace:
            marketplace.switch_to('origin')
            marketplace.delete()
            marketplace.switch_to('FIWARE Lab')
            select = self.driver.find_element_by_css_selector(
                '.se-select select')

            # Market list screenshot
            imgp = take_capture(
                self.driver, 'Wirecloud_Marketplace_plus_stores.png')
            add_image(imgp, get_position(select, 0.0, 1.0), 'store_filter.png')
            add_pointer(imgp, get_position(select, 0.7, 1.8), False)
            crop_down(imgp, select, 80)

            # marketplaces screenshot
            popup_menu = marketplace.open_menu()
            m_menu = popup_menu.get_entry('FIWARE Lab')
            ActionChains(self.driver).move_to_element(m_menu).perform()
            imgp = take_capture(self.driver, extra=8)
            add_pointer(imgp, get_position(m_menu, 0.8, 0.5))
            crop_down(imgp, popup_menu.element, 80)

            # Copy the previous to other one that uses it after
            # Change the name right
            shutil.copy2(imgp, image_path(extra=10, prepath=prepath))

            # Add marketplace
            m_menu = popup_menu.get_entry('Add new marketplace')
            ActionChains(self.driver).move_to_element(m_menu).perform()
            imgp = take_capture(self.driver, extra='AddNewMarketplace')
            add_pointer(imgp, get_position(m_menu, 0.8, 0.5))
            crop_down(imgp, popup_menu.element, 80)

            # Adding marketplace
            m_menu.click()
            dialog = self.driver.find_elements_by_css_selector(
                '.window_menu')[1]
            self.fill_form_input(dialog.find_element_by_css_selector('input[name="name"]'),
                                 'FIWARE Lab')
            self.fill_form_input(dialog.find_element_by_css_selector('input[name="url"]'),
                                 'https://marketplace.lab.fiware.org')
            Select(dialog.find_element_by_css_selector(
                'select')).select_by_index(1)
            imgp = take_capture(self.driver, extra='AddingFiwareMarketplace')
            crop_image(imgp, *create_box(dialog))

            # Cancel marketplace creation
            button = dialog.find_element_by_css_selector('button.se-btn:not(.btn-primary)')
            button.click()

            # Where are my resources
            btn = self.driver.find_element_by_css_selector(
                '.wc-toolbar .icon-archive')
            ActionChains(self.driver).move_to_element(btn).perform()
            time.sleep(0.3)  # wait tooltip animation
            imgp = take_capture(self.driver, "Wirecloud_switch_to_local")
            add_pointer(imgp, get_position(btn, 0.8, 0.5))
            crop_down(imgp, select, 80)

        with self.myresources_view as myresources:
            # Resources
            imgp = take_capture(self.driver, extra=9)

            btn = self.driver.find_element_by_css_selector(
                '.wc-toolbar .icon-cloud-upload')
            # Where are upload button
            ActionChains(self.driver).move_to_element(btn).perform()
            time.sleep(0.3)  # wait tooltip animation
            imgp = take_capture(self.driver, extra="UploadButton")
            add_pointer(imgp, get_position(btn, 0.5, 0.5))
            crop_down(imgp, myresources.search_in_results('Map Viewer').element, 80)

            # Upload dialog
            btn.click()
            dialog = self.driver.find_element_by_css_selector('.wc-upload-mac-dialog')
            imgp = take_capture(self.driver, extra='uploadNew')
            crop_image(imgp, *create_box(dialog))
            dialog.find_element_by_css_selector(
                '.btn-default.se-btn').click()  # cancel

            # Click in a widget for details
            container = get_first_displayed(
                # self.driver, '.se-bl-center-container .resource_list')
                self.driver, '.resource_list')
            widg = get_by_contains(
                container, '.resource.click_for_details', 'widget')
            # widg = container.find_element_by_css_selector('.resource.click_for_details')
            ActionChains(self.driver).move_to_element(widg).perform()
            imgp = take_capture(self.driver, 'Wirecloud_open_details')
            add_pointer(imgp, get_position(widg, 0.5, 0.5))
            crop_down(imgp, widg, 50)

            # Publish button
            widg.click()
            time.sleep(0.2)
            container = get_first_displayed(
                self.driver, '.advanced_operations')
            btn = get_by_text(container, '.se-btn', 'Publish')
            ActionChains(self.driver).move_to_element(btn).perform()  # wait?
            imgp = take_capture(self.driver, "Wirecloud_click_publish")
            add_pointer(imgp, get_position(btn, 0.8, 0.8))

            # Publish dialog
            btn.click()
            dialog = self.driver.find_element_by_css_selector(
                '.window_menu.publish_resource')
            dialog.find_element_by_css_selector(
                'input[value="admin/FIWARE Lab"]').click()
            select = dialog.find_element_by_css_selector('.se-select select')
            imgp = take_capture(
                self.driver, 'Wirecloud_publish_resource_store_select')
            add_image(imgp, get_position(select, 0.0, 1.0), 'store_list.png')
            add_pointer(imgp, get_position(select, 0.7, 1.8), False)
            crop_image(imgp, *create_box(dialog))

            get_by_text(dialog, 'button', 'Cancel').click()
            self.driver.find_element_by_css_selector(
                '.wirecloud_header_nav .btn-large .icon-caret-left').click()
    test_browsing_marketplace.tags = ('wirecloud-guide', 'ui-marketplace')

    @uses_extra_resources(list_resources)
    def test_building_mashup(self):
        def take_capture(*args, **kargs):
            return midd_take_capture(*args, prepath="building_mashup", **kargs)

        self.driver.set_window_size(1024, 768)
        self.login()
        self.create_workspace('History Info')
        self.open_menu().click_entry('History Info')
        self.wait_wirecloud_ready()

        add_widget_button = self.driver.find_element_by_css_selector('.wc-toolbar .icon-plus')
        ActionChains(self.driver).move_to_element(add_widget_button).perform()
        time.sleep(0.3)  # wait tooltip animation
        imgp = take_capture(self.driver, extra="19")
        add_pointer(imgp, get_position(add_widget_button, 0.8, 0.5))
        crop_down(imgp, self.driver.find_element_by_css_selector('.emptyWorkspaceInfoBox'))

        # Add to workspace
        with self.wallet as wallet:
            resource = wallet.search_in_results('Linear Graph')

            btn = resource.element.find_element_by_css_selector('.mainbutton')
            ActionChains(self.driver).move_to_element(btn).perform()
            time.sleep(0.3)  # wait tooltip animation
            imgp = take_capture(self.driver, extra=20)
            add_pointer(imgp, get_position(btn, 0.8, 0.8))
            crop_down(imgp, resource.element)

            widget = resource.instantiate()

        resize_widget(self.driver, widget, 12, 41)

        # get the widget and crop down
        imgp = take_capture(self.driver, extra=21)
        crop_down(imgp, widget.element)

        # Add a Map Viewer Widget
        map_viewer_widget = self.add_widget_to_mashup('Map Viewer')
        resize_widget(self.driver, map_viewer_widget, 8, 41)
        # get the widget and crop down
        ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector('.fiware-logo')).perform()
        time.sleep(0.3)  # Wait widget menu transition
        imgp = take_capture(self.driver, extra=22)

        widg_menu = map_viewer_widget.element.find_element_by_css_selector('.widget_menu')
        setts_btn = widg_menu.find_element_by_css_selector(
            '.buttons .icon-cogs')
        ActionChains(self.driver).move_to_element(setts_btn).perform()
        time.sleep(0.2)

        # get the widget and crop down
        imgp = take_capture(self.driver, extra=23)
        box = create_box(widg_menu, 40)
        box = (box[0] + 37, box[1] + 37, box[2] - 37, box[3])
        add_pointer(imgp, get_position(setts_btn, 0.5, 0.5))
        crop_image(imgp, *box)

        popup_menu = map_viewer_widget.open_menu()
        btn = popup_menu.get_entry('Settings')
        ActionChains(self.driver).move_to_element(btn).perform()
        # get the widget and crop down
        imgp = take_capture(self.driver, extra=24)
        add_pointer(imgp, get_position(btn))
        crop_image(imgp, *create_box(map_viewer_widget.element))
        # box = create_box(popup_menu.element, 130)
        # box = (box[0], box[1], box[2] + 100, box[3] + 100)
        # crop_image(imgp, *box)

        btn.click()
        dialog = get_first_displayed(self.driver, '.window_menu')
        self.fill_form_input(dialog.find_element_by_css_selector(
            'input[name="centerPreference"]'), 'Santander')
        self.fill_form_input(dialog.find_element_by_css_selector('input[name="initialZoom"]'), '14')
        self.fill_form_input(dialog.find_element_by_css_selector('input[name="zoomPreference"]'), '17')
        imgp = take_capture(self.driver, extra=25)
        crop_image(imgp, *create_box(dialog))

        dialog.find_element_by_css_selector(
            'button.btn-primary.se-btn').click()
        time.sleep(0.2)

        # Reload map viewer widget so it updates the view using the initial zoom and initial location
        popup = map_viewer_widget.open_menu()
        setts_btn = popup.get_entry("Reload")
        ActionChains(self.driver).move_to_element(setts_btn).perform()
        imgp = take_capture(self.driver, name='MapViewer_reload')
        box = create_box(popup.element, 40)
        box = (box[0] - 60, box[1], box[2], box[3])
        add_pointer(imgp, get_position(setts_btn, 0.8, 0.5), True)
        crop_image(imgp, *box)
        setts_btn.click()

        # Take a capture now that the map viewer widget is correctly placed
        map_viewer_widget.wait_loaded()
        imgp = take_capture(self.driver, name="MapViewer_configured")
        crop_image(imgp, *create_box(map_viewer_widget.element))

        imgp = take_capture(self.driver, extra=27)
        crop_down(
            imgp, get_by_contains(self.driver, '.fade.iwidget.in', 'Linear Graph'))

        dialog = self.driver.find_element_by_css_selector(
            '.wirecloud_app_bar')
        btn = dialog.find_element_by_css_selector(
            '.wc-toolbar .icon-puzzle-piece')
        ActionChains(self.driver).move_to_element(btn).perform()
        time.sleep(0.3)
        imgp = take_capture(self.driver, extra=28)
        add_pointer(imgp, get_position(btn, 0.8, 0.5))
        crop_down(imgp, btn, 60)

        def take_capture(*args, **kargs):
            return midd_take_capture(*args, prepath="wiring", **kargs)

        with self.wiring_view:
            ActionChains(self.driver).move_by_offset(0, 50).perform()
            self.wait_element_visible_by_css_selector('.wiring-view .se-alert-static-top')
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra='Empty_Wiring_Operators')
            crop_down(
                imgp, self.driver.find_element_by_css_selector(".wiring-view .se-alert-static-top"), 40)

            # Click in Find Components
            dialog = self.driver.find_element_by_css_selector('.wirecloud_app_bar')
            btn = dialog.find_element_by_css_selector('.wc-toolbar .icon-archive')
            ActionChains(self.driver).move_to_element(btn).perform()
            time.sleep(0.3)
            imgp = take_capture(self.driver, extra="Open_Find_Components")
            add_pointer(imgp, get_position(btn, 0.8, 0.5))
            crop_down(imgp, btn, 60)

            with self.wiring_view.component_sidebar as sidebar:
                # Create operator
                panel = self.driver.find_element_by_css_selector(".panel.panel-default.panel-components")
                btn = panel.find_element_by_css_selector(".se-btn.btn-create")
                ActionChains(self.driver).move_to_element(btn).perform()
                time.sleep(0.3)
                imgp = take_capture(self.driver, extra="Click_Create_Operator")
                add_pointer(imgp, get_position(btn, 0.5, 0.5))
                crop_down(imgp, btn, 60)

                sidebar.create_operator("NGSI source")

                # Dragging the NGSI source operator
                ent_oper = sidebar.find_operator_group_by_title("NGSI source").components[0].element
                ActionChains(self.driver).move_to_element(ent_oper).perform()

                time.sleep(0.3)

                imgp = take_capture(self.driver, extra="Wiring_NGSISource_Show")
                add_pointer(imgp, get_position(ent_oper, 0.8, 0.5))
                crop_down(imgp, ent_oper, 60)

                ActionChains(self.driver).click_and_hold(ent_oper).perform()
                imgp = take_capture(self.driver, extra='Wiring_NGSISource_drag')

                clon = get_by_contains(self.driver, ".panel.panel-default.component-draggable.component-operator.cloned.dragging", "NGSI source")
                add_pointer(imgp, get_position(clon, 0.5, 0.6))
                crop_down(imgp, clon, 100)

                # NGSI source added
                ActionChains(self.driver).move_to_element_with_offset(sidebar.section_diagram, 10, 10).release().perform()
                time.sleep(0.2)

                # NGSI source added
                entservc = get_by_contains(self.driver, ".panel.panel-default.component-draggable.component-operator", "NGSI source")
                imgp = take_capture(self.driver, extra='Wiring_NGSISource')
                add_pointer(imgp, get_position(entservc, 0.5, 0.5))
                crop_down(imgp, entservc, 250)

                ngsi_source_operator = sidebar._find_component_by_title("operator", "NGSI source")

                # Configure NGSI source
                self.configure_ngsi_source(ngsi_source_operator)

                # Add map iwidget
                mapsercvcomp = sidebar.add_component("widget", "Map Viewer", 500, 10)
                mapservc = mapsercvcomp.element
                imgp = take_capture(self.driver, extra='Wiring_NGSISource_MapViewer')
                add_pointer(imgp, get_position(mapservc, 0.5, 0.15), False)
                crop_down(imgp, mapservc, 10)

                # Over label
                labelprovideent = get_by_text(entservc, '.endpoint', 'Provide entity')
                ActionChains(self.driver).move_to_element(labelprovideent).perform()
                time.sleep(0.6)  # wait for color transition
                imgp = take_capture(self.driver, extra='Wiring_NGSISource_MapViewer_rec')
                # add_image(imgp, get_position(labelprovideent, 0.7, 0.7), 'popup1.png')
                add_pointer(imgp, get_position(labelprovideent, 0.6, 0.5))
                crop_down(imgp, mapservc, 10)

                sidebar.create_operator("NGSI Entity To PoI")
                poi_temp = sidebar.find_operator_group_by_title("NGSI Entity To PoI").components[0].element
                ActionChains(self.driver).click_and_hold(poi_temp).move_to_element_with_offset(sidebar.section_diagram, -30, 210).release().perform()
                time.sleep(0.2)

                poi_oper_w = sidebar._find_component_by_title("operator", "NGSI Entity To PoI")
                poiservc = poi_oper_w.element

                self.configure_ngsi_entity(poi_oper_w)

            imgp = take_capture(self.driver, extra='Wiring_NGSIEntity2PoI')
            add_pointer(imgp, get_position(poiservc, 0.5, 0.45))
            crop_down(imgp, mapservc, 10)

            ActionChains(self.driver).move_to_element(labelprovideent).perform()
            time.sleep(0.6)  # wait for color transition
            imgp = take_capture(self.driver, extra='Wiring_NGSIEntity2PoI_rec')
            add_pointer(imgp, get_position(labelprovideent, 0.6, 0.5))
            crop_down(imgp, mapservc, 10)

            # PoI connection
            fromc = labelprovideent.find_element_by_css_selector('.endpoint-anchor')
            labelentity = get_by_text(poiservc, '.endpoint', 'Entity')
            toc = labelentity.find_element_by_css_selector('.endpoint-anchor')

            ActionChains(self.driver).click_and_hold(fromc).move_by_offset(-100, 100).perform()
            time.sleep(0.2)
            imgp = take_capture(
                self.driver, extra='Wiring_NGSIEntity2PoI_connection')
            pos = get_position(fromc, 0.5, 0.5)
            pos = (pos[0] - 100, pos[1] + 100)
            add_pointer(imgp, pos)
            crop_down(imgp, mapservc, 10)

            ActionChains(self.driver).move_to_element(toc).release().perform()
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra='Wiring_NGSIEntity2PoI_c_done')
            add_pointer(imgp, get_position(labelentity, 0.6, 0.5))
            crop_down(imgp, mapservc, 10)

            labelPoI = get_by_text(poiservc, '.endpoint', 'PoI')
            fromc = labelPoI.find_element_by_css_selector('.endpoint-anchor')
            labelInsertUpdate = get_by_text(mapservc, '.endpoint', 'Insert/Update PoI')
            toc = labelInsertUpdate.find_element_by_css_selector('.endpoint-anchor')
            ActionChains(self.driver).drag_and_drop(
                fromc, toc).move_to_element(labelInsertUpdate).perform()
            time.sleep(0.6)
            imgp = take_capture(self.driver, extra='Wiring_End_1st_ph')
            add_pointer(imgp, get_position(labelInsertUpdate, 0.6, 0.5))
            crop_down(imgp, mapservc, 10)

        # Out wiring_view
        with map_viewer_widget:
            self.driver.execute_script('mapViewer.map.setMapTypeId("satellite");')
            WebDriverWait(self.driver, timeout=60).until(lambda driver: driver.execute_script('return Object.keys(mapViewer.mapPoiManager.getPoiList()).length !== 0;'))
        imgp = take_capture(self.driver, extra='MapViewer_with_entities')

        with map_viewer_widget:
            self.driver.execute_script('mapViewer.mapPoiManager.selectPoi(new Poi({id:"OUTSMART.NODE_3509"}));mapViewer.map.setZoom(16);')
        with widget:
            WebDriverWait(self.driver, timeout=30).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '#loadLayer.on')))
        imgp = take_capture(self.driver, extra='MapViewer_entity_details')

        with self.wiring_view as wiring:
            cons = wiring.find_connections()
            mapservcw = wiring.find_component_by_title("widget", "Map Viewer")
            mapservc = mapservcw.element

            #
            # Reshape arrow screenshots
            #

            mycon = cons[1]  # Can we know exactly if it's this?
            cprefs = mycon.display_preferences()

            custb = cprefs.get_entry("Customize")
            ActionChains(self.driver).move_to_element(custb).perform()
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra='reshape_arrow_pre')
            add_pointer(imgp, get_position(custb, 0.3, 0.3))
            crop_down(imgp, mapservc, 50)
            # Captura reshape_arrow_pre
            cprefs.click_entry("Customize")

            editablecon = [x for x in wiring.find_connections() if "editable" in x.class_list][0]

            _, ball_handler = editablecon.element.find_elements_by_css_selector(".handle-ball")

            move_elem(self.driver, ball_handler, 30, -30)
            _, ball_handler = editablecon.element.find_elements_by_css_selector(".handle-ball")
            imgp = take_capture(self.driver, extra='reshape_arrow2')
            add_pointer(imgp, get_position(ball_handler, 0.3, 0.3))
            crop_down(imgp, mapservc, 10)

            move_elem(self.driver, ball_handler, -30, 30)
            editablecons = [x for x in wiring.find_connections() if "editable" in x.class_list]
            if len(editablecons) == 0:
                wiring.find_connections()[1].display_preferences().click_entry("Customize")
                editablecon = [x for x in wiring.find_connections() if "editable" in x.class_list][0]

            _, ball_handler = editablecon.element.find_elements_by_css_selector(".handle-ball")
            imgp = take_capture(self.driver, extra='reshape_arrow1')
            add_pointer(imgp, get_position(ball_handler, 0.3, 0.3))
            crop_down(imgp, mapservc, 10)

            stopbutton = [x for x in wiring.find_connections() if "editable" in x.class_list][0].display_preferences().get_entry("Stop customizing")
            ActionChains(self.driver).move_to_element(stopbutton).perform()
            imgp = take_capture(self.driver, extra='reshape_arrow_stop')
            add_pointer(imgp, get_position(stopbutton, 0.3, 0.3))
            crop_down(imgp, mapservc, 10)
            stopbutton.click()

            #
            # Delete arrow screenshots
            #

            delcon = wiring.find_connections()[1]
            rmbtn = delcon.btn_remove
            ActionChains(self.driver).move_to_element(rmbtn.element).perform()
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra='delete_arrow1')
            add_pointer(imgp, get_position(rmbtn.element, 0.5, 0.4))
            crop_down(imgp, mapservc, 50)

            #
            # Minimize screenshots
            #

            ngsisw = wiring.find_component_by_title("operator", "NGSI source")
            collbtn = ngsisw.display_preferences().get_entry("Collapse")
            ActionChains(self.driver).move_to_element(collbtn).perform()
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra='minimize_option')
            add_pointer(imgp, get_position(collbtn, 0.3, 0.3))
            crop_down(imgp, mapservc, 10)
            collbtn.click()

            wiring.find_component_by_title("operator", "NGSI Entity To PoI").collapse_endpoints()

            imgp = take_capture(self.driver, extra=33)
            crop_down(imgp, mapservc, 10)

            movew = wiring.find_component_by_title("widget", "Map Viewer")
            move_elem(self.driver, movew.element, -70, 0)

            movew = wiring.find_component_by_title("operator", "NGSI Entity To PoI")
            move_elem(self.driver, movew.element, -20, 0)

            # Configure all other elements
            with wiring.component_sidebar as sidebar:
                sidebar.add_component("widget", "Linear Graph", 750, 10)
            with wiring.component_sidebar as sidebar:
                sidebar.create_operator("History Module to Linear Graph")
                sidebar.add_component("operator", "History Module to Linear Graph", 750, 100)

            mapw = wiring.find_component_by_title("widget", "Map Viewer")
            linw = wiring.find_component_by_title("widget", "Linear Graph")
            histw = wiring.find_component_by_title("operator", "History Module to Linear Graph")

            endp1 = mapw.find_endpoint_by_title("source", "PoI selected")
            endp2 = histw.find_endpoint_by_title("target", "Sensor Id")
            endp3 = histw.find_endpoint_by_title("source", "Historic Info")
            endp4 = linw.find_endpoint_by_title("target", "Data in")

            endp1.connect(endp2)
            endp3.connect(endp4)

            move_elem(self.driver, histw.element, 0, 35)

            take_capture(self.driver, extra='FinalWiring')

        with widget:
            WebDriverWait(self.driver, timeout=30).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '#loadLayer.on')))

        with map_viewer_widget:
            self.driver.execute_script('''
                var poi = mapViewer.mapPoiManager.getPoiList()["OUTSMART.NODE_3506"].poi;
                mapViewer.mapPoiManager.selectPoi(poi);
                mapViewer.map.setZoom(16);
                MashupPlatform.wiring.pushEvent('poiOutput', JSON.stringify(poi))
            ''')
            self.driver.execute_script('mapViewer.map.setMapTypeId("roadmap");')

        with widget:
            WebDriverWait(self.driver, timeout=30).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '#loadLayer.on')))
        take_capture(self.driver, extra=34)

        with widget:
            ActionChains(self.driver).move_to_element_with_offset(self.driver.find_element_by_css_selector('canvas'), -50, 0).click_and_hold().move_by_offset(50, 0).perform()

        lg_path = take_capture(self.driver, extra='linear_graph_zoom1')
        add_pointer(lg_path, get_position(widget.element, 0.31, 0.5), False)
        crop_image(lg_path, *create_box(widget.element))

        ActionChains(self.driver).release().perform()
        lg_path = take_capture(self.driver, extra='linear_graph_zoom2')
        crop_image(lg_path, *create_box(widget.element))

        # Public workspace!
        popup_menu = self.open_menu()
        m_menu = popup_menu.get_entry('Share')
        ActionChains(self.driver).move_to_element(m_menu).perform()
        imgp = take_capture(self.driver, extra='Public_Workspace_Menu')
        add_pointer(imgp, get_position(m_menu, 0.8, 0.5))
        crop_down(imgp, popup_menu.element, 80)
        m_menu.click()
        dialog = get_first_displayed(self.driver, '.wc-dashboard-share-dialog')
        public_b = dialog.find_element_by_css_selector('input[value="public"]')
        public_b.click()
        imgp = take_capture(self.driver, extra='Public_Workspace_Settings')
        add_pointer(imgp, get_position(public_b, 0.5, 0.5))
        crop_image(imgp, *create_box(dialog))
        dialog.find_element_by_css_selector('.btn-primary').click()

        # Embed mashup!
        popup_menu = self.open_menu()
        m_menu = popup_menu.get_entry('Embed')
        ActionChains(self.driver).move_to_element(m_menu).perform()
        imgp = take_capture(self.driver, extra='Embed_Workspace_Menu')
        add_pointer(imgp, get_position(m_menu, 0.8, 0.5))
        crop_down(imgp, popup_menu.element, 80)
        m_menu.click()
        dialog = get_first_displayed(
            self.driver, '.window_menu.embed-code-window-menu')
        imgp = take_capture(self.driver, extra='Embed_Dialog')
        crop_image(imgp, *create_box(dialog))
        dialog.find_element_by_css_selector('.btn-primary').click()

    test_building_mashup.tags = ('wirecloud-guide', 'ui-build-mashup')

    @uses_extra_workspace('admin', 'CoNWeT_History_Info_2.0.wgt')
    @uses_extra_workspace('admin', 'CoNWeT_MWD_Tutorial_2.0.wgt')
    def test_behaviour_mashup(self):
        def take_capture(*args, **kargs):
            return midd_take_capture(*args, prepath="behaviour_oriented_wiring", **kargs)
        self.driver.set_window_size(1024, 768)
        self.login(username="******", next="/admin/History Info")

        with self.wiring_view as wiring:
            btnbehav = wiring.btn_list_behaviours.element
            ActionChains(self.driver).move_to_element(btnbehav)
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra="list_behaviours_button")
            add_pointer(imgp, get_position(btnbehav, 0.8, 0.5))
            crop_down(imgp, btnbehav, 30)

            self.driver.execute_script("document.querySelector('.wiring-view .wiring-diagram').style.cssText = 'box-shadow: none; border: none;'")
            wc = self.driver.find_element_by_css_selector(".wiring-connections")

            with wiring.behaviour_sidebar as behaviour:
                beh = behaviour.behaviour_list[0]
                # for i, beh in enumerate(behaviour.behaviour_list):
                beh.activate()
            imgp = take_capture(self.driver, extra="santander_behaviour1")
            crop_image(imgp, *create_box(wc))

            with wiring.behaviour_sidebar as behaviour:
                beh = behaviour.behaviour_list[1]
                beh.activate()
            imgp = take_capture(self.driver, extra="santander_behaviour2")
            crop_image(imgp, *create_box(wc))

            with wiring.behaviour_sidebar as behaviour:
                self.driver.execute_script("document.querySelector('.wiring-view .wiring-diagram').style.cssText = ''")

                # Lock
                panelhead = self.driver.find_element_by_css_selector(".panel.panel-default.panel-behaviours .panel-heading")
                bnenable = panelhead.find_element_by_css_selector(".btn-enable")
                ActionChains(self.driver).move_to_element(bnenable).perform()
                time.sleep(0.2)
                tooltip = self.driver.find_element_by_css_selector(".tooltip.fade.bottom.in")
                imgp = take_capture(self.driver, extra="disable_behaviours_button")
                add_pointer(imgp, get_position(bnenable, 0.5, 0.5))
                panelheads = create_box(panelhead, 7)
                crop_image(imgp, left=panelheads[0], upper=panelheads[1], right=get_position(tooltip, 1.0, 1.0)[0] + 10, lower=get_position(tooltip, 1.0, 1.0)[1] + 10)

        self.change_current_workspace('MWD Tutorial')
        with self.wiring_view as wiring:
            with wiring.behaviour_sidebar as behaviour:
                beh = behaviour.behaviour_list[2]
                beh.activate()
                time.sleep(1)
                take_capture(self.driver, extra="general_aspect")

        with self.wiring_view as wiring:
            with wiring.behaviour_sidebar as behaviour:
                btncreate = behaviour.btn_create_behaviour
                ActionChains(self.driver).move_to_element(btncreate.element).perform()
                time.sleep(0.2)
                imgp = take_capture(self.driver, extra="create_behaviour_button")
                add_pointer(imgp, get_position(btncreate.element, 0.5, 0.5))
                btncreate.click()

                createform = self.driver.find_element_by_css_selector(".behaviour-create-form")
                imgp = take_capture(self.driver, extra="behaviour_form")
                crop_image(imgp, *create_box(createform))
                get_by_text(createform, '.se-btn', 'Cancel').click()

                firstbehav = behaviour.active_behaviour
                prefs = firstbehav.display_preferences()
                btnprefs = prefs.get_entry("Settings")
                ActionChains(self.driver).move_to_element(btnprefs).perform()
                time.sleep(0.2)
                imgp = take_capture(self.driver, extra="behaviour_settings_option")
                add_pointer(imgp, get_position(btnprefs, 0.5, 0.5))
                prefs.close()

                btnrm = firstbehav.btn_remove
                ActionChains(self.driver).move_to_element(btnrm.element).perform()
                time.sleep(0.2)
                imgp = take_capture(self.driver, extra="remove_behaviour_button")
                add_pointer(imgp, get_position(btnrm.element, 0.5, 0.5))

            techniciancomponent = wiring.find_component_by_title("widget", "Technician List")
            rmbtn = techniciancomponent.btn_remove
            ActionChains(self.driver).move_to_element(rmbtn.element).perform()
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra="remove_component")
            add_pointer(imgp, get_position(rmbtn.element, 0.5, 0.5))

            targetend = techniciancomponent.find_endpoint_by_title("target", "Technician")
            connection = [x for x in wiring.find_connections() if x.targetid == targetend.id][0]
            rmbtn = connection.btn_remove
            ActionChains(self.driver).move_to_element(rmbtn.element).perform()
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra="remove_connection")
            add_pointer(imgp, get_position(rmbtn.element, 0.5, 0.5))

            with wiring.behaviour_sidebar as behaviour:
                behaviour.create_behaviour("Test", "Testing")
                lastbehav = behaviour.behaviour_list[-1]
                lastbehav.activate()

            techniciancomponent = wiring.find_component_by_title("widget", "Technician List")
            addbtn = techniciancomponent.btn_add
            ActionChains(self.driver).move_to_element(addbtn.element).perform()
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra="component_share_button")
            add_pointer(imgp, get_position(addbtn.element, 0.5, 0.5))

            targetend = techniciancomponent.find_endpoint_by_title("target", "Query")
            connection = [x for x in wiring.find_connections() if x.targetid == targetend.id][0]
            addbtn = connection.btn_add
            ActionChains(self.driver).move_to_element(addbtn.element).perform()
            time.sleep(0.2)
            imgp = take_capture(self.driver, extra="connection_share_button")
            add_pointer(imgp, get_position(addbtn.element, 0.5, 0.5))

        self.create_workspace('Enable Behaviour Work')
        with self.wiring_view as wiring:
            with wiring.behaviour_sidebar as behaviour:
                # UnLock
                panelhead = self.driver.find_element_by_css_selector(".panel.panel-default.panel-behaviours .panel-heading")
                bnenable = panelhead.find_element_by_css_selector(".btn-enable")
                ActionChains(self.driver).move_to_element(bnenable).perform()
                time.sleep(0.2)
                tooltip = self.driver.find_element_by_css_selector(".tooltip.fade.bottom.in")
                imgp = take_capture(self.driver, extra="enable_behaviours_button")
                add_pointer(imgp, get_position(bnenable, 0.5, 0.5))
                panelheads = create_box(panelhead, 7)
                crop_image(imgp, left=panelheads[0], upper=panelheads[1], right=get_position(tooltip, 1.0, 1.0)[0] + 10, lower=get_position(tooltip, 1.0, 1.0)[1] + 10)

    test_behaviour_mashup.tags = ('wirecloud-guide', 'ui-behaviour')
Esempio n. 6
0
class FiWareSeleniumTestCase(WirecloudSeleniumTestCase):

    fixtures = ('selenium_test_data', 'fiware_test_data')
    servers = {
        'http': {
            'marketplace.example.com':
            DynamicWebServer(),
            'repository.example.com':
            LocalFileSystemServer(
                os.path.join(os.path.dirname(__file__), 'test-data',
                             'responses', 'repository')),
            'static.example.com':
            LocalFileSystemServer(
                os.path.join(os.path.dirname(__file__), 'test-data',
                             'responses', 'static')),
            'store.example.com':
            DynamicWebServer(fallback=LocalFileSystemServer(
                os.path.join(os.path.dirname(__file__), 'test-data',
                             'responses', 'store'))),
            'store2.example.com':
            DynamicWebServer(fallback=LocalFileSystemServer(
                os.path.join(os.path.dirname(__file__), 'test-data',
                             'responses', 'store2'))),
            'orion.example.com:1026':
            DynamicWebServer(),
        },
    }
    tags = ('wirecloud-selenium', 'wirecloud-fiware',
            'wirecloud-fiware-selenium')

    @classmethod
    def setUpClass(cls):

        WirecloudSeleniumTestCase.setUpClass.__func__(cls)

        cls.store_list_response = read_response_file('responses',
                                                     'marketplace',
                                                     'store_list.xml')
        cls.store1_offerings = read_response_file('responses', 'marketplace',
                                                  'store1_offerings.xml')
        cls.store2_offerings = read_response_file('responses', 'marketplace',
                                                  'store2_offerings.xml')

    def setUp(self):

        super(FiWareSeleniumTestCase, self).setUp()

        self.network._servers['http']['marketplace.example.com'].clear()
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/registration/stores/',
            {'content': self.store_list_response})
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/Store%201/offerings',
            {'content': self.store1_offerings})
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/Store%202/offerings',
            {'content': self.store2_offerings})
        self.network._servers['http']['store.example.com'].clear()
        self.network._servers['http']['store2.example.com'].clear()
        self.network._servers['http']['orion.example.com:1026'].clear()

    def test_add_fiware_marketplace(self):

        self.login()

        with self.marketplace_view as marketplace:
            marketplace.add('fiware', 'http://marketplace.example.com/',
                            'fiware')
            widget_offering = marketplace.search_in_results(
                'Smart City Lights application')
            self.assertIsNotNone(widget_offering)

    test_add_fiware_marketplace.tags = tags + ('wirecloud-markets-selenium', )

    def test_add_public_fiware_marketplace(self):

        self.login()

        with self.marketplace_view as marketplace:
            marketplace.add('fiware',
                            'http://marketplace.example.com/',
                            'fiware',
                            public=True)
            widget_offering = marketplace.search_in_results(
                'Smart City Lights application')
            self.assertIsNotNone(widget_offering)

    test_add_public_fiware_marketplace.tags = tags + (
        'wirecloud-markets-selenium', )

    def test_delete_fiware_marketplace(self):

        self.login(username='******')

        with self.marketplace_view as marketplace:
            marketplace.switch_to('fiware')
            marketplace.delete()

    test_delete_fiware_marketplace.tags = tags + (
        'wirecloud-markets-selenium', )

    def test_ngsi_available_to_widgets(self):

        self.login(username="******", next="/admin/Workspace")

        with self.myresources_view as myresources:
            myresources.upload_resource('Wirecloud_ngsi-test-widget_1.0.1.wgt',
                                        'Wirecloud NGSI API test widget')

        with self.create_widget('Wirecloud NGSI API test widget'):
            api_element = self.driver.find_element_by_id('api_available')
            self.assertEqual(api_element.text, 'Yes')

    @uses_extra_resources(('Wirecloud_ngsi-test-widget_1.0.1.wgt', ))
    def test_ngsi_api_reports_failures(self):

        self.login(username="******", next="/admin/Workspace")

        widget = self.create_widget('Wirecloud NGSI API test widget')

        # Change widget settings
        widget.open_menu().click_entry('Settings')
        dialog = FormModalTester(
            self, self.wait_element_visible(".wc-component-preferences-modal"))
        dialog.get_field("ngsi_server").set_value(
            'http://orion.example.com:1026')
        dialog.get_field("use_user_fiware_token").click()
        dialog.accept()

        # Check the widget raises an error
        with widget:
            WebDriverWait(self.driver,
                          2).until(lambda driver: driver.find_element_by_id(
                              'api_available').text == 'Yes')
            self.driver.find_element_by_css_selector('.btn-primary').click()
            alert = self.wait_element_visible('.alert-error p')
            self.assertEqual(alert.text, 'Unexpected error code: 404')

    def test_objectstorage_available_to_widgets(self):

        self.login(username="******", next="/admin/Workspace")

        with self.myresources_view as myresources:
            myresources.upload_resource(
                'Wirecloud_objectstorage-test-widget_1.0.1.wgt',
                'Wirecloud Object Storage API test widget')

        with self.create_widget('Wirecloud Object Storage API test widget'):
            api_element = self.driver.find_element_by_id('api_available')
            self.assertEqual(api_element.text, 'Yes')

    @uses_extra_resources(('Wirecloud_objectstorage-test-widget_1.0.1.wgt', ))
    def test_objectstorage_reports_failures(self):

        self.login(username="******", next="/admin/Workspace")

        with self.create_widget('Wirecloud Object Storage API test widget'):
            api_element = self.driver.find_element_by_id('api_available')
            self.assertEqual(api_element.text, 'Yes')
            self.driver.find_element_by_css_selector('.btn-primary').click()
            WebDriverWait(
                self.driver,
                10).until(lambda driver: driver.find_element_by_css_selector(
                    '.btn-primary:not(.disabled)'))

            tenant_id_step = self.driver.find_element_by_id('tenantId')
            self.assertEqual(tenant_id_step.text, 'Fail')
            alert = self.wait_element_visible('.alert-error')
            self.assertEqual(alert.text, 'Failure!')

    def test_marketplace_keyword_search(self):

        response_text = read_response_file('responses', 'marketplace',
                                           'keyword_search.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/search/offerings/fulltext/test',
            {'content': response_text})

        self.login(username='******')

        with self.marketplace_view as marketplace:
            marketplace.switch_to('fiware')

            marketplace.search('test')
            self.assertIsNotNone(
                marketplace.search_in_results('Smart City Lights application'))

    test_marketplace_keyword_search.tags = tags + (
        'wirecloud-markets-selenium', )

    def test_marketplace_filter_by_store(self):

        self.login(username='******')

        with self.marketplace_view as marketplace:
            marketplace.switch_to('fiware')

            catalogue_base_element = marketplace.wait_catalogue_ready()
            store_select = Select(
                catalogue_base_element.find_element_by_css_selector(
                    '.store_select select'))
            store_select.select_by_value('Store 1')

            # Check results from store 1 are not displayed
            self.assertIsNone(marketplace.search_in_results('Weather widget'))

            # Check results from store 2 are displayed
            self.assertIsNotNone(
                marketplace.search_in_results('Test Operator'))
            self.assertIsNotNone(
                marketplace.search_in_results('Smart City Lights application'))

    test_marketplace_filter_by_store.tags = tags + (
        'wirecloud-markets-selenium', )

    def test_marketplace_offering_buttons(self):

        response_text = read_response_file('responses', 'marketplace',
                                           'keyword_search.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/search/offerings/fulltext/test',
            {'content': response_text})

        self.login(username='******')

        with self.marketplace_view as marketplace:
            marketplace.switch_to('fiware')

            free_offering = marketplace.search_in_results('Weather widget')
            button = free_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Free')

            simple_price_offering = marketplace.search_in_results(
                'Test Operator')
            button = simple_price_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, '10 €')

            complex_price_offering = marketplace.search_in_results(
                'Smart City Lights application')
            button = complex_price_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Purchase')

            arbitrary_offering = marketplace.search_in_results(
                'Arbitrary Offering')
            button = arbitrary_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Details')

            invalid_offering = marketplace.search_in_results(
                'Invalid Resources')
            button = invalid_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Details')

            # Purchased offerings
            pack_offering = marketplace.search_in_results('MultimediaPack')
            button = pack_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Install')

            open_offering = marketplace.search_in_results('Open Offering')
            button = open_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Install')

    def test_marketplace_offering_list_when_store_down(self):

        response_text = read_response_file('responses', 'marketplace',
                                           'keyword_search.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/search/offerings/fulltext/test',
            {'content': response_text})
        old_store = self.network._servers['http']['store.example.com']
        del self.network._servers['http']['store.example.com']

        try:
            self.login(username='******')

            with self.marketplace_view as marketplace:
                marketplace.switch_to('fiware')

                # Weather widget comes from an accesible store (store2 is online)
                free_offering = marketplace.search_in_results('Weather widget')
                button = free_offering.element.find_element_by_css_selector(
                    '.mainbutton')
                self.assertEqual(button.text, 'Free')

                arbitrary_offering = marketplace.search_in_results(
                    'Arbitrary Offering')
                button = arbitrary_offering.element.find_element_by_css_selector(
                    '.mainbutton')
                self.assertEqual(button.text, 'Details')

                open_offering = marketplace.search_in_results('Open Offering')
                button = open_offering.element.find_element_by_css_selector(
                    '.mainbutton')
                self.assertEqual(button.text, 'Install')

                # All offerings from store 1 should have a Details button (as it is currently down)
                for offering_name in ('Test Operator',
                                      'Smart City Lights application',
                                      'MultimediaPack'):
                    offering = marketplace.search_in_results(offering_name)
                    button = offering.element.find_element_by_css_selector(
                        '.mainbutton')
                    self.assertEqual(button.text, 'Details')

        finally:
            self.network._servers['http']['store.example.com'] = old_store

    def test_other_offering_buttons(self):

        offering_name = 'Arbitrary Offering'

        self.login(username='******')

        with self.marketplace_view as marketplace:

            marketplace.switch_to('fiware')

            with marketplace.search_in_results(offering_name) as offering:
                buttons = len(
                    offering.details.find_elements_by_css_selector(
                        '.panel .se-btn:not(.plain), .se-notebook-tab-content .se-btn'
                    ))
                self.assertEqual(buttons, 0)

    def test_store_upload_resource(self):

        self.network._servers['http']['store.example.com'].add_response(
            'POST', '/api/offering/resources', {'content': ''})

        self.login(username='******')

        with self.myresources_view as myresources:
            with myresources.search_in_results('Test') as resource:

                resource.advanced_operation('Publish')

                window_menu = self.wait_element_visible(
                    '.window_menu.publish_resource')
                window_menu.find_element_by_css_selector(
                    'input[value="user_with_markets/fiware"]').click()
                self.driver.find_element_by_xpath(
                    "//*[contains(@class, 'window_menu')]//*[text()='Accept']"
                ).click()
                self.wait_wirecloud_ready()

                window_menus = self.driver.find_elements_by_css_selector(
                    '.window_menu')
                self.assertEqual(len(window_menus), 1,
                                 'Resource was not uploaded')

    def _buy_offering(self):
        bought_response_text = read_response_file('responses', 'store2',
                                                  'service2_bought.json')
        self.network._servers['http']['store2.example.com'].add_response(
            'GET', '/mystore/api/offering/offerings/service2.rdf',
            {'content': bought_response_text})
        dialog = FormModalTester(self,
                                 self.wait_element_visible(".wc-buy-modal"))
        dialog.accept()
        WebDriverWait(self.driver, 10).until(EC.staleness_of(dialog.element))
        self.wait_wirecloud_ready()

    def check_store_buy_offering(self, from_details):

        response_text = read_response_file('responses', 'marketplace',
                                           'keyword_search.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/search/offerings/fulltext/test',
            {'content': response_text})
        self.network._servers['http']['store2.example.com'].add_response(
            'POST', '/mystore/api/contracting/form',
            {'content': str('{"url": "' + self.live_server_url + '"}')})
        response_text = read_response_file(
            'responses', 'marketplace', 'store2_weatherwidget_offering.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/Store%202/offering/WeatherWidget',
            {'content': response_text})

        self.login(username='******')

        with self.marketplace_view as marketplace:
            marketplace.switch_to('fiware')

            free_offering = marketplace.search_in_results('Weather widget')
            if from_details:
                with free_offering:
                    free_offering.details.find_element_by_css_selector(
                        '.mainbutton').click()
                    self._buy_offering()
                    mainbutton = free_offering.details.find_element_by_css_selector(
                        '.mainbutton')
                    self.assertEqual(mainbutton.text, 'Uninstall')
            else:
                free_offering.element.find_element_by_css_selector(
                    '.mainbutton').click()
                self._buy_offering()

            marketplace.wait_catalogue_ready()

            free_offering = marketplace.search_in_results('Weather widget')
            button = free_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Uninstall')

    def test_store_buy_offering(self):
        self.check_store_buy_offering(False)

    def test_store_buy_offering_from_details(self):
        self.check_store_buy_offering(True)

    def check_offering_install(self, offering_name, resources):

        self.login(username='******')

        with self.marketplace_view as marketplace:

            with marketplace.myresources as myresources:
                for resource_name in resources:
                    self.assertIsNone(
                        myresources.search_in_results(resource_name))

            marketplace.switch_to('fiware')

            offering = marketplace.search_in_results(offering_name)
            button = offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Install')

            self.scroll_and_click(button)
            self.wait_wirecloud_ready()
            marketplace.wait_catalogue_ready()
            offering = marketplace.search_in_results(offering_name)
            button = offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Uninstall')

            with marketplace.myresources as myresources:
                for resource_name in resources:
                    self.assertIsNotNone(
                        myresources.search_in_results(resource_name))

    def test_install_store_offering(self):

        response_text = read_response_file('responses', 'store2',
                                           'service2_bought.json')
        self.network._servers['http']['store2.example.com'].add_response(
            'GET', '/mystore/api/offering/offerings/service2.rdf',
            {'content': response_text})
        offering_name = 'Weather widget'
        resources = ('Weather Widget Example', )

        self.check_offering_install(offering_name, resources)

    def test_install_store_open_offering(self):

        offering_name = 'Open Offering'
        resources = ('Weather Widget Example', )

        self.check_offering_install(offering_name, resources)

    def test_install_store_offering_embedded(self):

        response_text = read_response_file('responses', 'store2',
                                           'service_embedded_bought.json')
        self.network._servers['http']['store2.example.com'].add_response(
            'GET', '/mystore/api/offering/offerings/service2.rdf',
            {'content': response_text})
        offering_name = 'Weather widget'
        resources = (
            'TestMashupEmbedded',
            'nonavailable-widget',
            'nonavailable-operator',
        )

        self.check_offering_install(offering_name, resources)

    def test_install_store_pack_offering(self):

        offering_name = 'MultimediaPack'
        resources = (
            'YouTube Browser',
            'Input Box',
        )

        self.check_offering_install(offering_name, resources)

    @uses_extra_resources((
        'responses/static/CoNWeT__Input Box Widget__1.0__CoNWeT_input-box_1.0.wgt',
        'responses/static/CoNWeT__Youtube Browser Widget__3.0__CoNWeT_youtube-browser_3.0.wgt',
    ),
                          public=False,
                          users=('user_with_markets', ))
    def test_uninstall_store_pack_offering(self):

        offering_name = 'MultimediaPack'
        resources = (
            'YouTube Browser',
            'Input Box',
        )

        self.login(username='******')

        with self.marketplace_view as marketplace:

            with marketplace.myresources as myresources:
                for resource_name in resources:
                    self.assertIsNotNone(
                        myresources.search_in_results(resource_name))

            marketplace.switch_to('fiware')

            free_offering = marketplace.search_in_results(offering_name)
            button = free_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Uninstall')

            button.click()
            self.wait_wirecloud_ready()

            free_offering = marketplace.search_in_results(offering_name)
            button = free_offering.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, 'Install')

            with marketplace.myresources as myresources:
                for resource_name in resources:
                    self.assertIsNone(
                        myresources.search_in_results(resource_name))

    def check_install_individual_resource_from_store_offering(self, last):

        offering_name = 'MultimediaPack'
        resource_name = 'YouTube Browser'

        self.login(username='******')

        with self.marketplace_view as marketplace:

            with marketplace.myresources as myresources:
                myresources.search(resource_name)
                self.assertIsNone(myresources.search_in_results(resource_name))

            marketplace.switch_to('fiware')

            with marketplace.search_in_results(offering_name) as free_offering:
                mainbutton = free_offering.details.find_element_by_css_selector(
                    '.mainbutton')
                self.assertEqual(mainbutton.text, 'Install')

                tabs = free_offering.details.find_elements_by_css_selector(
                    '.se-notebook-tab')
                for tab in tabs:
                    tab.location_once_scrolled_into_view
                    if tab.text == 'Resources':
                        self.scroll_and_click(tab)
                        break
                resources = free_offering.details.find_elements_by_css_selector(
                    '.offering_resource_list .se-model-table-row')
                resource = resources[1]
                button = resource.find_element_by_css_selector('.se-btn')
                self.assertEqual(button.text, 'Install')
                button.click()

                self.wait_wirecloud_ready()
                self.assertEqual(button.text, 'Uninstall')

                if last:
                    self.assertEqual(mainbutton.text, 'Uninstall')
                else:
                    self.assertEqual(mainbutton.text, 'Install')

            with marketplace.myresources as myresources:
                self.assertIsNotNone(
                    myresources.search_in_results(resource_name))

    def test_install_individual_resource_from_store_offering(self):
        self.check_install_individual_resource_from_store_offering(False)

    @uses_extra_resources((
        'responses/static/CoNWeT__Input Box Widget__1.0__CoNWeT_input-box_1.0.wgt',
    ),
                          public=False,
                          users=('user_with_markets', ))
    def test_install_last_individual_resource_from_store_offering(self):
        self.check_install_individual_resource_from_store_offering(True)

    def test_marketplace_navigation(self):

        response_text = read_response_file(
            'responses', 'marketplace', 'store2_weatherwidget_offering.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/Store%202/offering/WeatherWidget',
            {'content': response_text})
        response_text = read_response_file(
            'responses', 'marketplace', 'store1_multimediapack_offering.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/Store%201/offering/MultimediaPack',
            {'content': response_text})

        self.login(username="******")

        # Fill navigation history
        with self.marketplace_view as marketplace:
            marketplace.switch_to('fiware')
            with marketplace.search_in_results('MultimediaPack'):
                pass
            with marketplace.search_in_results('Weather widget'):
                pass

        # Check navigation history has been filled correctly
        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.get_current_view() == 'marketplace')
        self.assertEqual(self.marketplace_view.get_current_marketplace_name(),
                         'fiware')

        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'details')
        self.assertEqual(self.marketplace_view.get_current_resource(),
                         'Weather widget')

        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'search')

        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'details')
        self.assertEqual(self.marketplace_view.get_current_resource(),
                         'MultimediaPack')

        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'search')

        self.driver.back()
        WebDriverWait(
            self.driver,
            timeout=5).until(lambda driver: self.marketplace_view.
                             get_current_marketplace_name() == 'origin')
        self.assertEqual(self.marketplace_view.get_subview(), 'search')

        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            WEC.workspace(self, owner="wirecloud", name="home"))

        # Replay navigation history
        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.get_current_view() == 'marketplace')
        self.assertEqual(self.marketplace_view.get_current_marketplace_name(),
                         'origin')
        self.assertEqual(self.marketplace_view.get_subview(), 'search')

        self.driver.forward()
        WebDriverWait(
            self.driver,
            timeout=5).until(lambda driver: self.marketplace_view.
                             get_current_marketplace_name() == 'fiware')
        self.assertEqual(self.marketplace_view.get_subview(), 'search')

        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'details')
        self.assertEqual(self.marketplace_view.get_current_resource(),
                         'MultimediaPack')

        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'search')

        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'details')
        self.assertEqual(self.marketplace_view.get_current_resource(),
                         'Weather widget')

        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'search')

        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            WEC.workspace(self, owner="wirecloud", name="home"))

    test_marketplace_navigation.tags = tags + ('wirecloud-markets-selenium', )
Esempio n. 7
0
class MarketplaceTestCase(WirecloudTestCase):

    tags = ('wirecloud-fiware', 'wirecloud-fiware-marketplace',
            'wirecloud-noselenium')
    fixtures = ('selenium_test_data', 'fiware_test_data')
    servers = {
        'http': {
            'marketplace.example.com':
            DynamicWebServer(),
            'repository.example.com':
            DynamicWebServer(fallback=LocalFileSystemServer(
                os.path.join(os.path.dirname(__file__), 'test-data',
                             'responses', 'repository'))),
            'store2.example.com':
            DynamicWebServer(fallback=LocalFileSystemServer(
                os.path.join(os.path.dirname(__file__), 'test-data',
                             'responses', 'store2'))),
        },
    }
    maxDiff = None

    @classmethod
    def setUpClass(cls):

        super(MarketplaceTestCase, cls).setUpClass()

        cls.store_list_response = cls.read_response_file(
            'responses', 'marketplace', 'store_list.xml')
        cls.store2_offerings = cls.read_response_file('responses',
                                                      'marketplace',
                                                      'store2_offerings.xml')

    def setUp(self):

        super(MarketplaceTestCase, self).setUp()

        self.market_adaptor = MarketAdaptor('http://marketplace.example.com')
        self.network._servers['http']['marketplace.example.com'].clear()
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/registration/stores/',
            {'content': self.store_list_response})
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/Store%202/offerings',
            {'content': self.store2_offerings})
        self.network._servers['http']['repository.example.com'].clear()

    @classmethod
    def read_response_file(self, *response):
        f = open(
            os.path.join(os.path.dirname(__file__), 'test-data', *response))
        contents = f.read()
        f.close()

        return contents

    def test_marketplace_complain_about_relative_urls(self):

        self.assertRaises(ValueError, MarketAdaptor, 'path')
        self.assertRaises(ValueError, MarketAdaptor, '/path')
        self.assertRaises(ValueError, MarketAdaptor,
                          '//marketplace.example.com/path')

    def test_marketplace_handle_url_trailing_slashes(self):

        test_adaptor = MarketAdaptor('http://marketplace.example.com')
        self.assertEqual(test_adaptor._marketplace_uri,
                         'http://marketplace.example.com/')

        test_adaptor = MarketAdaptor('http://marketplace.example.com///')
        self.assertEqual(test_adaptor._marketplace_uri,
                         'http://marketplace.example.com/')

    def test_marketplace_must_ignore_params_query_and_framgent(self):

        test_adaptor = MarketAdaptor(
            'http://marketplace.example.com/?query=a#a')
        self.assertEqual(test_adaptor._marketplace_uri,
                         'http://marketplace.example.com/')

    def test_marketplace_get_all_offerings_from_store(self):

        store2_offerings = self.read_response_file('responses', 'marketplace',
                                                   'store2_offerings.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/offering/store/Store%202/offerings',
            {'content': store2_offerings})
        result = self.market_adaptor.get_all_services_from_store('Store 2')
        result['resources'] = list(result['resources'])
        expected_result = json.loads(
            self.read_response_file(
                'results',
                'test_marketplace_get_all_offerings_from_store.json'))

        self.assertEqual(result, expected_result)

    def test_marketplace_get_all_offerings_from_store_repository_failing(self):

        old_repository = self.network._servers['http'][
            'repository.example.com']
        del self.network._servers['http']['repository.example.com']

        try:
            result = self.market_adaptor.get_all_services_from_store('Store 2')

            self.assertEqual(result, {'resources': ()})
        finally:
            self.network._servers['http'][
                'repository.example.com'] = old_repository

    def test_marketplace_get_all_offerings_from_store_bad_usdl_content(self):

        self.network._servers['http']['repository.example.com'].add_response(
            'GET', '/CoNWeT/service2.rdf', {'content': 'invalid content'})
        result = self.market_adaptor.get_all_services_from_store('Store 2')
        result['resources'] = list(result['resources'])
        expected_result = json.loads(
            self.read_response_file(
                'results',
                'test_marketplace_get_all_offerings_from_store_bad_usdl_content.json'
            ))

        self.assertEqual(result, expected_result)

    def test_marketplace_get_all_offerings_from_store_failures_are_cached(
            self):
        def build_invalid_usdl_response(method, url, *args, **kwargs):
            build_invalid_usdl_response.counter += 1
            return {
                'headers': {
                    'Content-Type': 'application/rdf+xml',
                    'Content-Length': 5,
                },
                'content': 'invalid content'
            }

        build_invalid_usdl_response.counter = 0

        self.network._servers['http']['repository.example.com'].add_response(
            'GET', '/CoNWeT/service2.rdf', build_invalid_usdl_response)
        result1 = self.market_adaptor.get_all_services_from_store('Store 2')
        result2 = self.market_adaptor.get_all_services_from_store('Store 2')
        self.assertEqual(result1, result2)
        self.assertEqual(build_invalid_usdl_response.counter, 1)

    def test_marketplace_keyword_search(self):

        response_text = self.read_response_file('responses', 'marketplace',
                                                'keyword_search.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/search/offerings/fulltext/test',
            {'content': response_text})
        result = self.market_adaptor.full_text_search('', 'test', {})
        result['resources'] = list(result['resources'])
        expected_result = json.loads(
            self.read_response_file('results',
                                    'test_marketplace_keyword_search.json'))

        self.assertEqual(result, expected_result)

    def test_marketplace_get_store_info(self):

        response_text = self.read_response_file('responses', 'marketplace',
                                                'store1_info.xml')
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/registration/store/Store%201', {'content': response_text})
        result = self.market_adaptor.get_store_info('Store 1')
        expected_result = json.loads(
            self.read_response_file('results',
                                    'test_marketplace_get_store_info.json'))

        self.assertEqual(result, expected_result)

    def test_marketadaptor_views_require_authentication(self):

        client = Client()

        urls = [
            reverse('wirecloud.fiware.market_resource_collection',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware'
                    }),
            reverse('wirecloud.fiware.store_resource_collection',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware',
                        'store': 'store1'
                    }),
            reverse('wirecloud.fiware.market_offering_entry',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware',
                        'store': 'store1',
                        'offering_id': 'id'
                    }),
            reverse('wirecloud.fiware.market_full_search',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware',
                        'search_string': 'test'
                    }),
            reverse('wirecloud.fiware.store_search',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware',
                        'store': 'store1',
                        'search_string': 'test'
                    }),
            reverse('wirecloud.fiware.store_collection',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware'
                    }),
        ]

        for url in urls:
            response = client.get(url, HTTP_ACCEPT='application/json')
            self.assertEqual(response.status_code, 401)

        url = reverse('wirecloud.fiware.store_start_purchase',
                      kwargs={
                          'market_user': '******',
                          'market_name': 'fiware',
                          'store': 'store1'
                      })
        response = client.post(url,
                               '{"offering_url": ""}',
                               content_type='application/json; charset=UTF-8',
                               HTTP_ACCEPT='application/json')
        self.assertEqual(response.status_code, 401)

    def test_marketadaptor_views_unexpected_response(self):

        client = Client()
        client.login(username='******', password='******')

        self.network._servers['http']['marketplace.example.com'].clear()
        self.network._servers['http']['marketplace.example.com'].add_response(
            'GET', '/registration/stores/', {'status_code': 503})

        urls = [
            reverse('wirecloud.fiware.market_resource_collection',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware'
                    }),
            reverse('wirecloud.fiware.store_resource_collection',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware',
                        'store': 'store1'
                    }),
            reverse('wirecloud.fiware.market_offering_entry',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware',
                        'store': 'store1',
                        'offering_id': 'id'
                    }),
            reverse('wirecloud.fiware.market_full_search',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware',
                        'search_string': 'test'
                    }),
            reverse('wirecloud.fiware.store_search',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware',
                        'store': 'store1',
                        'search_string': 'test'
                    }),
            reverse('wirecloud.fiware.store_collection',
                    kwargs={
                        'market_user': '******',
                        'market_name': 'fiware'
                    }),
        ]

        for url in urls:
            response = client.get(url, HTTP_ACCEPT='application/json')
            self.assertEqual(response.status_code, 502)

        url = reverse('wirecloud.fiware.store_start_purchase',
                      kwargs={
                          'market_user': '******',
                          'market_name': 'fiware',
                          'store': 'store1'
                      })
        response = client.post(url,
                               '{"offering_url": ""}',
                               content_type='application/json; charset=UTF-8',
                               HTTP_ACCEPT='application/json')
        self.assertEqual(response.status_code, 502)

    def test_marketplace_get_all_stores_emtpy(self):

        self.network._servers['http']['marketplace.example.com'].clear()

        response = self.market_adaptor.get_all_stores()
        self.assertEqual(response, [])
Esempio n. 8
0
class MarketManagementSeleniumTestCase(WirecloudSeleniumTestCase):

    servers = {
        'http': {
            'wcatalogue.example.com':
            DynamicWebServer(fallback=LocalFileSystemServer(
                os.path.join(os.path.dirname(__file__), 'test-data',
                             'responses', 'wcatalogue'))),
        },
    }
    tags = ('wirecloud-selenium', 'wirecloud-markets',
            'wirecloud-markets-selenium')
    use_search_indexes = False

    def check_resource_buttons(self, marketplace, resources, button_text=None):
        for resource_name in resources:
            resource = marketplace.search_in_results(resource_name)
            self.assertIsNotNone(resource)
            button = resource.element.find_element_by_css_selector(
                '.mainbutton')
            self.assertEqual(button.text, button_text)

    def test_no_marketplaces(self):

        Market.objects.all().delete()

        self.login('normuser')
        with self.marketplace_view:
            alert = self.wait_element_visible('.marketplace-error-view .alert')
            self.assertIsNotNone(alert)
            self.assertTrue(alert.is_displayed())

    def test_default_marketplace(self):

        self.login('normuser')
        with self.marketplace_view as marketplace:
            self.assertEqual(marketplace.get_current_marketplace_name(),
                             'origin')

    def test_add_marketplace(self):

        self.login()
        with self.marketplace_view as marketplace:
            marketplace.add('remote', 'http://wcatalogue.example.com',
                            'wirecloud')
            self.check_resource_buttons(
                marketplace, ('New Widget', 'New Operator', 'New Mashup'),
                'Install')
            self.check_resource_buttons(
                marketplace, ('Test', 'TestOperator', 'Test Mashup'),
                'Uninstall')

        self.login('normuser', 'admin')
        with self.marketplace_view as marketplace:
            popup_menu = marketplace.open_menu()
            popup_menu.check(must_be_absent=('remote', ))

    def test_add_public_marketplace(self):

        self.login()
        with self.marketplace_view as marketplace:
            marketplace.add('remote',
                            'http://wcatalogue.example.com',
                            'wirecloud',
                            public=True)
            self.check_resource_buttons(
                marketplace, ('New Widget', 'New Operator', 'New Mashup'),
                'Install')
            self.check_resource_buttons(
                marketplace, ('Test', 'TestOperator', 'Test Mashup'),
                'Uninstall')

        self.login('normuser', 'admin')
        with self.marketplace_view as marketplace:
            marketplace.switch_to('remote')
            self.check_resource_buttons(
                marketplace, ('New Widget', 'New Operator', 'New Mashup'),
                'Install')
            self.check_resource_buttons(
                marketplace, ('Test', 'TestOperator', 'Test Mashup'),
                'Uninstall')

    def test_add_duplicated_marketplace(self):

        self.login('user_with_markets', 'admin')
        with self.marketplace_view as marketplace:
            marketplace.add('deleteme',
                            'http://localhost:8080',
                            'wirecloud',
                            expect_error=True)

    def test_delete_marketplace(self):

        self.login('user_with_markets', 'admin')

        with self.marketplace_view as marketplace:
            marketplace.switch_to('deleteme')
            marketplace.delete()

    def test_global_marketplace_are_deletable_by_superusers(self):

        self.login('normuser', 'admin')

        with self.marketplace_view as marketplace:
            marketplace.switch_to('origin')
            marketplace.open_menu().check((), (), ('Delete marketplace', ))

        self.login('admin', 'admin')

        with self.marketplace_view as marketplace:
            marketplace.switch_to('origin')
            marketplace.delete()

    def test_publish_option_not_available_if_not_targets(self):

        Market.objects.all().delete()
        self.login(username='******')

        with self.myresources_view as myresources:
            with myresources.search_in_results('Test') as resource:
                resource.advanced_operation('Publish')
                modal = ModalTester(
                    self, self.wait_element_visible('.window_menu.message'))
                modal.accept()

    def test_marketplace_navigation(self):

        self.login(username="******")

        # Fill navigation history
        with self.marketplace_view as marketplace:
            with marketplace.search_in_results('Test'):
                pass
            with marketplace.search_in_results('Test Mashup'):
                pass
            marketplace.switch_to('deleteme')

        # Check navigation history has been filled correctly
        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.get_current_view() == 'marketplace')
        self.assertEqual(self.marketplace_view.get_current_marketplace_name(),
                         'deleteme')
        self.assertEqual(self.marketplace_view.get_subview(), 'search')

        self.driver.back()
        WebDriverWait(
            self.driver,
            timeout=5).until(lambda driver: self.marketplace_view.
                             get_current_marketplace_name() == 'origin')
        self.assertEqual(self.marketplace_view.get_subview(), 'search')
        self.assertEqual(self.marketplace_view.get_current_marketplace_name(),
                         'origin')

        self.driver.back()
        # get_current_resource also checks we are at the details subview
        WebDriverWait(self.driver,
                      timeout=5).until(lambda driver: self.marketplace_view.
                                       get_current_resource() == 'Test Mashup')

        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'search')

        self.driver.back()
        # get_current_resource also checks we are at the details subview
        WebDriverWait(self.driver,
                      timeout=5).until(lambda driver: self.marketplace_view.
                                       get_current_resource() == 'Test')

        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'search')

        self.driver.back()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.get_current_view() == 'workspace')

        # Replay navigation history
        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.get_current_view() == 'marketplace')
        self.assertEqual(self.marketplace_view.get_current_marketplace_name(),
                         'origin')
        self.assertEqual(self.marketplace_view.get_subview(), 'search')

        self.driver.forward()
        # get_current_resource also checks we are at the details subview
        WebDriverWait(self.driver,
                      timeout=5).until(lambda driver: self.marketplace_view.
                                       get_current_resource() == 'Test')

        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'search')

        self.driver.forward()
        # get_current_resource also checks we are at the details subview
        WebDriverWait(self.driver,
                      timeout=5).until(lambda driver: self.marketplace_view.
                                       get_current_resource() == 'Test Mashup')

        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.marketplace_view.get_subview() == 'search')
        self.assertEqual(self.marketplace_view.get_current_marketplace_name(),
                         'origin')

        self.driver.forward()
        WebDriverWait(
            self.driver,
            timeout=5).until(lambda driver: self.marketplace_view.
                             get_current_marketplace_name() == 'deleteme')
        self.assertEqual(self.marketplace_view.get_subview(), 'search')

        self.driver.forward()
        WebDriverWait(self.driver, timeout=5).until(
            lambda driver: self.get_current_view() == 'workspace')