Example #1
0
    def share_with_social(self, check=True):
        """Step to share with social.

        Args:
            check (bool): flag whether check step or no

        Raises:
            AssertionError: if check is failed
        """
        page = self.app.page_top_movies
        page.button_share.click()

        if check:
            social_rows = page.list_social_share.rows

            assert_that(social_rows[0].link_social.href,
                        starts_with('http://www.facebook.com/sharer'))
            assert_that(social_rows[1].link_social.href,
                        starts_with('http://twitter.com/intent/tweet'))
            assert_that(social_rows[2].link_social.href,
                        starts_with('mailto:?subject=Check'))
            assert_that(social_rows[3].link_social.href,
                        starts_with('http://www.imdb.com/chart/top'))
            social_rows[3].click()
            assert_that(pyperclip.paste(),
                        equal_to('http://www.imdb.com/chart/top'))
Example #2
0
    def test_list_returns_all_if_omniscient_nd_collector_view_but_no_ownership(
            self):
        view = TestResourceViewCollector()

        request = HttpRequest()
        request.method = 'GET'
        request.META['HTTP_AUTHORIZATION'] = \
            'Bearer correct-token'

        settings.USE_DEVELOPMENT_USERS = False
        signon = govuk_signon_mock(
            permissions=['omniscient', 'collector-view'])
        with HTTMock(signon):
            response = view.get(request)

            try:
                json_response = json.loads(response.content)
            except ValueError:
                json_response = None

            assert_that(response.status_code, is_(200))
            assert_that(len(json_response), is_(2))
            assert_that(json_response, contains_inanyorder(
                has_entry("name", starts_with(
                    self.__class__.collector_type1.name)),
                has_entry("name", starts_with(
                    self.__class__.collector_type2.name))))
Example #3
0
def test_plugin_echo_renders_node(caplog):
    stream = StringIO('''
    - name: test0
      echo: "{{ node }}"
    - name: test1
      echo: "{{ node }}"
    - name: test2
      echo: "{{ node }}"
    ''')
    document = loader.ordered_load(stream)

    nodes = TopLevel.build(document)

    context = Context()

    for index, node in enumerate(nodes):
        node.execute(context)

        assert_that(len(caplog.records), equal_to(11))
        assert_that(caplog.records[1].message,
                    starts_with("test%d is starting" % index))
        assert_that(caplog.records[2].message,
                    starts_with("| %s" % platform.node()))
        assert_that(caplog.records[3].message,
                    starts_with("test%d has finished" % index))

        caplog.clear()
    def test_get_cram_metadata(self):
        meta_list = arrayexpress.get_cram_metadata('oryza_sativa')
        assert_that(len(meta_list), greater_than(100))

        first = meta_list[0]
        assert_that(first.study_id, starts_with('DRP'))
        assert_that(first.sample_ids[0], starts_with('SAMD'))
        assert_that(first.biorep_id, starts_with('DRR'))
        assert_that(first.run_ids[0], starts_with('DRR'))
        assert_that(first.ftp_location, starts_with('ftp://ftp.ebi.ac.uk/pub/databases/arrayexpress/data/atlas/rnaseq'))
def test_traverse_to_nondict():
    with assert_raises(ValueError) as caught:
        registry.get_by_binding("some.example.here it goes bad")

    assert_that(caught.exception.message,
                starts_with("Cannot traverse subtree of type int"))

    with assert_raises(ValueError) as caught:
        registry.get_by_binding("data.here.setting.here it goes bad")

    assert_that(caught.exception.message,
                starts_with("Cannot traverse subtree of type list"))
Example #6
0
def test_attaches_with_capture_exist(report_for, test):
    report = report_for("""
    import sys
    def test_x():
        sys.stdout.write('STDOUT HELLO')
        sys.stderr.write('STDERR HELLO')
        %s
    """ % test)

    assert_that(report.find('.//attachment'), contains_inanyorder(
        has_entry('title', starts_with('Captured stdout')),
        has_entry('title', starts_with('Captured stderr'))))
Example #7
0
def test_traverse_to_nondict():
    with assert_raises(ValueError) as caught:
        registry.get_by_binding("some.example.here it goes bad")

    assert_that(caught.exception.message,
                starts_with("Cannot traverse subtree of type int"))

    with assert_raises(ValueError) as caught:
        registry.get_by_binding("data.here.setting.here it goes bad")

    assert_that(caught.exception.message,
                starts_with("Cannot traverse subtree of type list"))
Example #8
0
def test_attaches_with_capture_exist(report_for, test):
    report = report_for("""
    import sys
    def test_x():
        sys.stdout.write('STDOUT HELLO')
        sys.stderr.write('STDERR HELLO')
        %s
    """ % test)

    assert_that(
        report.find('.//attachment'),
        contains_inanyorder(has_entry('title', starts_with('Captured stdout')),
                            has_entry('title',
                                      starts_with('Captured stderr'))))
Example #9
0
def assert_command_error(response, prefix, hint=None):
    """Verifies structure and basic content of command processor errors"""

    print tostring(response)

    err_el = response.find("error")
    assert_that(err_el, is_not(None))
    desc_el = err_el.find("desc")
    assert_that(desc_el, is_not(None))
    assert_that(desc_el.text, starts_with(prefix))

    if hint:
        hint_el = err_el.find("hint")
        assert_that(hint_el, is_not(None))
        assert_that(hint_el.text, starts_with(hint))
Example #10
0
def test_create_device_null_parameters():
    response = confd.devices.post(
        mac=None,
        template_id=None,
        plugin=None,
        vendor=None,
        version=None,
        description=None,
        options=None,
    )
    response.assert_created('devices')

    assert_that(
        response.item,
        has_entries(
            mac=none(),
            template_id=none(),
            status='not_configured',
            plugin=none(),
            vendor=none(),
            version=none(),
            description=none(),
            options=none(),
        ),
    )

    provd_device = provd.devices.get(response.item['id'])
    assert_that(provd_device['config'], starts_with('autoprov'))
Example #11
0
def test_basic_auth_default_realm():
    """
    Basic auth uses the convention that the metadata's name is the realm.

    """
    graph = create_object_graph(name="example", testing=True)

    @graph.app.route("/unauthorized")
    @graph.audit
    @graph.basic_auth.required
    def unauthorized():
        raise Exception("Should not be raised!")

    client = graph.app.test_client()

    response = client.get("/unauthorized")
    assert_that(response.status_code, is_(equal_to(401)))
    data = loads(response.get_data().decode("utf-8"))
    assert_that(data, has_entries(dict(
        code=401,
        message=starts_with("The server could not verify that you are authorized to access the URL requested"),
        retryable=False,
        context={"errors": []},
    )))
    assert_that(response.headers["WWW-Authenticate"], is_(equal_to('Basic realm="example"')))
Example #12
0
def test_basic_auth():
    """
    Basic auth prevents resource access.

    """
    config = {
        "BASIC_AUTH_REALM": "microcosm",
    }

    graph = create_object_graph(name="example", testing=True, loader=lambda metadata: config)

    @graph.app.route("/unauthorized")
    @graph.audit
    @graph.basic_auth.required
    def unauthorized():
        raise Exception("Should not be raised!")

    client = graph.app.test_client()

    response = client.get("/unauthorized")
    assert_that(response.status_code, is_(equal_to(401)))
    data = loads(response.get_data().decode("utf-8"))
    assert_that(data, has_entries(dict(
        code=401,
        message=starts_with("The server could not verify that you are authorized to access the URL requested"),
        retryable=False,
        context={"errors": []},
    )))
    assert_that(response.headers["WWW-Authenticate"], is_(equal_to('Basic realm="microcosm"')))
Example #13
0
 def test_auth_by_session(self):
     response = self.deform_client.auth(
         auth_type='session',
         auth_key='test'
     )
     assert_that(response, instance_of(SessionAuthClient))
     assert_that(response.auth_header, starts_with('SessionId'))
def track_edition_page(parent, number=None):
    name_condition = starts_with(
        "track_edition_page"
    ) if not number else "track_edition_page_" + str(number)
    return TrackEditionPageDriver.find_single(parent, TrackEditionPage,
                                              named(name_condition),
                                              showing_on_screen())
Example #15
0
    def create_backup(self, volume_name, backup_name, description=None,
                      container=None, check=True):
        """Step to create volume backup."""
        tab_volumes = self._tab_volumes()

        with tab_volumes.table_volumes.row(
                name=volume_name).dropdown_menu as menu:
            menu.button_toggle.click()
            menu.item_create_backup.click()

        with tab_volumes.form_create_backup as form:
            form.field_name.value = backup_name

            if description is not None:
                form.field_description.value = description

            if container is not None:
                form.field_container.value = container

            form.submit()

        if check:
            self.close_notification('success')
            row = self._tab_backups().table_backups.row(name=backup_name)
            row.wait_for_status(status='Available')
            if description is not None:
                assert_that(row.cell('description').value,
                            starts_with(description[:30]))
Example #16
0
def test_get():
    response = confd.asterisk.pjsip.doc.get()
    response.assert_ok()
    assert_that(
        response.json,
        has_entries(
            aor=has_entries(),
            auth=has_entries(),
            contact=has_entries(),
            endpoint=all_of(
                has_entries(direct_media_method=has_entries(
                    name='direct_media_method',
                    default='invite',
                    synopsis='Direct Media method type',
                    description=starts_with('Method for setting up'),
                    choices=has_entries(
                        invite='',
                        reinvite='Alias for the "invite" value.',
                        update='',
                    ),
                )),
                not_(has_entries(type='endpoint')),
            ),
            system=has_entries(),
            transport=has_entries(),
        ),
    )
Example #17
0
    def test_connect_timeout(self):
        with self.assertRaises(ConnectTimeout) as expect:
            self.client("10.0.0.0", "whatever", "whatever", connect_timeout=1)

        assert_that(
            str(expect.exception),
            starts_with("Timed out while connecting to 10.0.0.0 on port"))
Example #18
0
def yearly_account(context):
    """Check that the yearly membership information for an account is accurate."""
    acct_repository = AccountRepository(context.db)
    membership = acct_repository.get_active_account_membership(
        context.accounts["foo"].id)
    assert_that(membership.type, equal_to(YEARLY_MEMBERSHIP))
    assert_that(membership.payment_account_id, starts_with("cus"))
def test_configure_engine():
    """
    Engine factory should work with zero configuration.

    """
    graph = create_object_graph(name="example", testing=True)
    engine = graph.postgres

    assert_that(engine, is_(instance_of(Engine)))

    # engine has expected configuration
    assert_that(
        str(engine.url),
        starts_with("postgresql://example:@"),
    )

    assert_that(
        str(engine.url),
        ends_with(":5432/example_test_db"),
    )

    # engine supports connections
    with engine.connect() as connection:
        row = connection.execute("SELECT 1;").fetchone()
        assert_that(row[0], is_(equal_to(1)))
Example #20
0
def test_get_failed_tests_returns_no_failed_tests_when_request_fails(mock_print, mock_get):
    failed_tests = get_failed_tests([100, 101, 102], "test-url", "test-token")

    check_mocked_functions_called(mock_get, mock_print)
    assert_that(failed_tests, equal_to([]), "Failed tests should not be returned when the request failed")
    request_failed_message = mock_print.call_args[0][0]
    assert_that(request_failed_message, starts_with("##vso[task.logissue type=warning]No failed tests were found"))
Example #21
0
def test_werkzeug_http_error():
    """
    Explicit HTTP errors are reported as expected.

    """
    graph = create_object_graph(name="example", testing=True)

    @graph.app.route("/not_found")
    @graph.audit
    def not_found():
        raise NotFound

    client = graph.app.test_client()

    response = client.get("/not_found")
    assert_that(response.status_code, is_(equal_to(404)))
    data = response.json
    assert_that(
        data,
        has_entries(
            dict(
                code=404,
                context={
                    "errors": [],
                },
                message=starts_with(
                    "The requested URL was not found on the server."),
                retryable=False,
            )))
    def test_archive_manifest_url_request__url_with_auth(self):
        url = self.archive_service.archive_manifest_url_request().set_path(
            '/path/to/manifest.zip').set_ttl(600).url()

        assert_that(
            url,
            starts_with('//archive-fish.wixmp.com/path/to/manifest.zip?auth='))
def test_column_field_can_be_marked_as_internal(engine):
    Base = declarative_base()

    class AuthorRecord(Base):
        __tablename__ = "author"

        c_id = Column(Integer, primary_key=True)
        c_name = Column(Unicode, nullable=False)

    class Author(SqlAlchemyObjectType):
        __model__ = AuthorRecord

        id = column_field(AuthorRecord.c_id, internal=True)
        name = column_field(AuthorRecord.c_name)

    class Root(RootType):
        authors = many(lambda: select(Author))

    Base.metadata.create_all(engine)

    result = executor(Root)("""{
        authors {
            id
        }
    }""",
                            context=QueryContext(session=Session(engine)))
    assert_that(
        result,
        is_invalid_result(errors=contains_inanyorder(
            has_string(starts_with('Cannot query field "id"')), )),
    )
Example #24
0
def has_test_case(name, *matchers):
    return has_property(
        'test_cases',
        has_item(
            all_of(
                any_of(has_entry('fullName', ends_with(name)),
                       has_entry('name', starts_with(name))), *matchers)))
Example #25
0
def check_dissociate_when_not_associated(line1, device1, line2, device2):
    with a.line_device(line1, device1), a.line_device(line2, device2):
        response = confd.lines(line1['id']).devices(device2['id']).delete()
        response.assert_deleted()

        provd_device1 = provd.devices.get(device1['id'])
        assert_that(provd_device1['config'], not_(starts_with('autoprov')))

        provd_device2 = provd.devices.get(device2['id'])
        assert_that(provd_device2['config'], not_(starts_with('autoprov')))

        response = confd.lines(line1['id']).get()
        assert_that(response.item, has_entries(device_id=device1['id']))

        response = confd.lines(line2['id']).get()
        assert_that(response.item, has_entries(device_id=device2['id']))
Example #26
0
    def show_movie_details(self, movie_number, by_title=True, check=True):
        """Step to show detailed info about movie.

        Args:
            movie_number (int): number of movie item in movies list
            by_title (bool): flag to use title link to navigate or icon link
            check (bool): flag whether check step or no

        Raises:
            AssertionError: if check is failed
        """
        page = self.app.page_top_movies
        row_movie = page.table_movies.rows[movie_number]

        movie_title = row_movie.link_title.value
        movie_year = row_movie.label_year.value.strip('()')
        movie_rating = row_movie.cell('imdb_rating').value

        if by_title:
            row_movie.link_title.click()
        else:
            row_movie.link_poster.click()

        if check:
            with self.app.page_movie_details as page:
                assert_that(self.app.current_page, equal_to(page))
                assert_that(page.label_title.value, starts_with(movie_title))
                assert_that(page.link_year.value, equal_to(movie_year))
                assert_that(page.label_rating.value, equal_to(movie_rating))
Example #27
0
    def test_sending_a_new_confirmation_mail(self, user):
        email_uuid = user['emails'][0]['uuid']

        self.client.users.request_confirmation_email(user['uuid'], email_uuid)

        url = self.get_last_email_url()
        url = url.replace('https://', 'http://')
        result = requests.get(url)
        assert_that(
            result,
            has_properties(
                status_code=200,
                headers=has_entries('Content-Type',
                                    starts_with('text/x-test; charset=')),
                text='Custom template',
            ),
        )

        updated_user = self.client.users.get(user['uuid'])
        assert_that(
            updated_user,
            has_entries(emails=contains(
                has_entries(address='*****@*****.**', confirmed=True))),
        )

        assert_http_error(409, self.client.users.request_confirmation_email,
                          user['uuid'], email_uuid)
        assert_http_error(404, self.client.users.request_confirmation_email,
                          UNKNOWN_UUID, email_uuid)
        assert_http_error(
            404,
            self.client.users.request_confirmation_email,
            user['uuid'],
            UNKNOWN_UUID,
        )
Example #28
0
 def test_generate_ntiid(self):
     ntiid = generate_ntiid(u'FOO', now=datetime.utcfromtimestamp(1000))
     assert_that(
         ntiid,
         starts_with(
             'tag:nextthought.com,2011-10:NTI-FOO-system_19700101001640_000000'
         ))
Example #29
0
    def create_backup(self, volume_name, backup_name=None, description=None,
                      container=None, check=True):
        """Step to create volume backup."""
        backup_name = backup_name or next(utils.generate_ids('backup'))

        page_volumes = self._page_volumes()

        with page_volumes.table_volumes.row(
                name=volume_name).dropdown_menu as menu:
            menu.button_toggle.click()
            menu.item_create_backup.click()

        with page_volumes.form_create_backup as form:
            form.field_name.value = backup_name

            if description is not None:
                form.field_description.value = description

            if container is not None:
                form.field_container.value = container

            form.submit()

        if check:
            self.close_notification('success')
            self._tab_backups().table_backups.row(
                name=backup_name, status='Available').wait_for_presence(
                config.UI_LONG_TIMEOUT)
            row = self._tab_backups().table_backups.row(name=backup_name)
            if description is not None:
                assert_that(row.cell('description').value,
                            starts_with(description[:30]))

        return backup_name
Example #30
0
 def test_list_path_with_non_leaf(self):
     """
     Given
         a path that contains a single non-leaf child node
     When
         path is listed
     Then
         return a single non-leaf node
     """
     with patch_urlopen() as mock_urlopen:
         mock_response = Mock()
         mock_response.read.return_value = """
         [
             {
                 "leaf": 0,
                 "context": {},
                 "text" : "servers",
                 "expandable": 1,
                 "id": "servers",
                 "allowChildren": 1
             }
         ]
         """
         mock_urlopen.return_value = mock_response
         result = self.ds.list_path(path=["a", "b", "c"])
         T.assert_equal(1, len(result))
         expected_servers_dict = {"type": "dir", "name": u"servers", "children": None}
         T.assert_dicts_equal(expected_servers_dict, result[0])
         mock_urlopen.assert_called_with(match(starts_with("http://dontcare.com:8080/metrics/find")))
         mock_urlopen.assert_called_with(match(contains_string("query=a.b.c.*")))
def test_configure_engine():
    """
    Engine factory should work with zero configuration.

    """
    graph = create_object_graph(name="example", testing=True)
    engine = graph.postgres

    assert_that(engine, is_(instance_of(Engine)))

    # engine has expected configuration
    assert_that(
        str(engine.url),
        starts_with("postgresql://example:@"),
    )

    assert_that(
        str(engine.url),
        ends_with(":5432/example_test_db"),
    )

    # engine supports connections
    with engine.connect() as connection:
        row = connection.execute("SELECT 1;").fetchone()
        assert_that(row[0], is_(equal_to(1)))
Example #32
0
    def create_snapshot(self,
                        volume_name,
                        snapshot_name=None,
                        description=None,
                        check=True):
        """Step to create volume snapshot."""
        snapshot_name = snapshot_name or next(utils.generate_ids('snapshot'))

        tab_volumes = self._tab_volumes()

        with tab_volumes.table_volumes.row(
                name=volume_name).dropdown_menu as menu:
            menu.button_toggle.click()
            menu.item_create_snapshot.click()

        with tab_volumes.form_create_snapshot as form:
            form.field_name.value = snapshot_name
            if description is not None:
                form.field_description.value = description
            form.submit()

        if check:
            self.close_notification('info')
            row = self._tab_snapshots().table_snapshots.row(name=snapshot_name)
            row.wait_for_status('Available', timeout=config.EVENT_TIMEOUT * 2)
            if description is not None:
                assert_that(
                    row.cell('description').value,
                    starts_with(description[:30]))

        return snapshot_name
 def test_list_path_with_non_leaf(self):
     """
     Given
         a path that contains a single non-leaf child node
     When
         path is listed
     Then
         return a single non-leaf node
     """
     with patch_urlopen() as mock_urlopen:
         mock_response = Mock()
         mock_response.read.return_value = """
         [
             {
                 "leaf": 0,
                 "context": {},
                 "text" : "servers",
                 "expandable": 1,
                 "id": "servers",
                 "allowChildren": 1
             }
         ]
         """
         mock_urlopen.return_value = mock_response
         result = self.ds.list_path(path=['a','b','c'])
         T.assert_equal(1, len(result))
         expected_servers_dict = {'type': 'dir', 'name': u'servers', 'children': None}
         T.assert_dicts_equal(expected_servers_dict, result[0])
         mock_urlopen.assert_called_with(match(starts_with('http://dontcare.com:8080/metrics/find')))
         mock_urlopen.assert_called_with(match(contains_string('query=a.b.c.*')))
Example #34
0
def check_dissociate(line, device):
    with a.line_device(line, device, check=False):
        response = confd.lines(line['id']).devices(device['id']).delete()
        response.assert_deleted()

        provd_device = provd.devices.get(device['id'])
        assert_that(provd_device['config'], starts_with('autoprov'))
Example #35
0
def assert_provd_config(user, line, provd_config):
    assert_that(
        provd_config,
        has_entries(
            id=is_not(starts_with('autoprov')),
            configdevice='defaultconfigdevice',
            deletable=True,
            parent_ids=has_items('base', 'defaultconfigdevice'),
            raw_config=has_entries(
                X_key='',
                config_version=1,
                X_xivo_user_uuid=user['uuid'],
                X_xivo_phonebook_profile=line['context'],
                exten_dnd='*25',
                exten_fwd_unconditional='*21',
                exten_fwd_no_answer='*22',
                exten_fwd_busy='*23',
                exten_fwd_disable_all='*20',
                exten_pickup_call='*8',
                exten_voicemail='*98',
                exten_park=none(),
                exten_pickup_group=none(),
            ),
        ),
    )
Example #36
0
def test_signals_project_to_open_when_open_action_triggered(driver, using):
    signal = ValueMatcherProbe("open project", "project.tgit")

    _ = show_page(make_project_history(make_snapshot(name="project", path="project.tgit")),
                  on_load_project=signal.received)

    driver.open_recent_project(starts_with("project"), using=using)
    driver.check(signal)
Example #37
0
 def test_auth_by_token_with_project_id(self):
     response = self.deform_client.auth(
         auth_type='token',
         auth_key='test',
         project_id='some_project'
     )
     assert_that(response, instance_of(ProjectClient))
     assert_that(response.auth_header, starts_with('Token'))
Example #38
0
    def test_list(self):
        NodeFactory(name='foo-node-1')
        NodeFactory(name='foo-node-2')

        status_code, json_response = self.get()

        assert_that(status_code, is_(200))
        assert_that(len(json_response), is_(2))
        assert_that(json_response[0]['name'], starts_with('foo-node'))
def test_page_contents():
    """The setup page should appear correctly."""
    assert_that(browser.url, ends_with("#/setup"))

    assert_that(browser.title, starts_with("Dashboard Creation |"))

    header = browser.find_by_css("body > .content-holder > .container > h1")
    assert_that(header.first.text, is_("Dashboard Creation"))

    assert browser.is_text_present(STEP_TITLES[1])
Example #40
0
def test_called_ok_explicitly_twice_fail(desc):
    expected = 'was called 3 times'
    matcher = called_n_times(2)
    mock = Mock()
    mock()
    mock()
    mock()

    ok = matcher.matches(mock, desc)
    assert_that(ok, equal_to(False))
    assert_that(str(desc), starts_with(expected))
Example #41
0
def has_test_case(name, *matchers):
    return has_property('test_cases',
                        has_item(
                            all_of(
                                any_of(
                                    has_entry('fullName', ends_with(name)),
                                    has_entry('name', starts_with(name))
                                ),
                                *matchers
                            )
                        )
                        )
    def test_submit_task(self):
        task = SubmitToEna(species='oryza_sativa', study_id='DRP000315', sample_ids=['SAMD00009892', 'SAMD00009893'],
                           biorep_id='E-GEOD-35288', run_ids=['DRR000745', 'DRR000746'], assembly_used='IRGSP-1.0',
                           ftp_location='ftp://ftp.ebi.ac.uk/pub/databases/arrayexpress/data/atlas/rnaseq/DRR016/DRR016438/DRR016438.cram',
                           test=True)
        has_completed = luigi.build([task], local_scheduler=True)
        assert_that(has_completed, is_(True))

        output = task.output().open('r').read()
        expected = '\t'.join(['E-GEOD-35288', 'oryza_sativa',
                              'ftp://ftp.ebi.ac.uk/pub/databases/arrayexpress/data/atlas/rnaseq/DRR016/DRR016438/DRR016438.cram',
                              '298b38e7ab3342bd3b7c5c9fac07422c'])
        assert_that(output, starts_with(expected))
        assert_that(output, contains_string('\tERA'))
Example #43
0
 def test_spotlightify_handles_department_and_agency(self):
     agency = AgencyWithDepartmentFactory()
     self.dashboard.organisation = agency
     self.dashboard.validate_and_save()
     assert_that(
         self.dashboard.spotlightify(),
         has_entry(
             'department',
             has_entries({
                 'title': starts_with('department'),
                 'abbr': starts_with('abbreviation')
             })
         )
     )
     assert_that(
         self.dashboard.spotlightify(),
         has_entry(
             'agency',
             has_entries({
                 'title': starts_with('agency'),
                 'abbr': starts_with('abbreviation')
             })
         )
     )
    def test_request_has_correct_headers(self, mock_request):
        mock_request.__name__ = 'request'

        client = BaseClient('http://admin.api', 'token')
        client._get('/foo')

        mock_request.assert_called_with(
            'GET',
            'http://admin.api/foo',
            headers=match_equality(has_entries({
                'Accept': 'application/json',
                'Authorization': 'Bearer token',
                'User-Agent': starts_with('Performance Platform Client'),
            })),
            data=None,
        )
    def test_post_has_content_type_header(self, mock_request):
        mock_request.__name__ = 'request'

        client = BaseClient('http://admin.api', 'token')
        client._post('/foo', 'bar')

        mock_request.assert_called_with(
            'POST',
            'http://admin.api/foo',
            headers = match_equality(has_entries({
                'Accept': 'application/json',
                'Authorization': 'Bearer token',
                'User-Agent': starts_with('Performance Platform Client'),
                'Content-Type': 'application/json',
            })),
            data='bar',
        )
Example #46
0
 def test_class_level_list_for_spotlight_returns_minimal_json_array(self):
     dashboard_two = DashboardFactory()
     organisation = ServiceFactory()
     dashboard_two.organisation = organisation
     dashboard_two.service_cache = organisation
     agency = organisation.parents.first()
     dashboard_two.agency_cache = agency
     dashboard_two.department_cache = agency.parents.first()
     dashboard_two.validate_and_save()
     DashboardFactory(published=False)
     list_for_spotlight = Dashboard.list_for_spotlight()
     assert_that(list_for_spotlight['page-type'], equal_to('browse'))
     assert_that(len(list_for_spotlight['items']), equal_to(2))
     assert_that(list_for_spotlight['items'][0],
                 has_entries({
                     'slug': starts_with('slug'),
                     'title': 'title',
                     'dashboard-type': 'transaction'
                 }))
     assert_that(list_for_spotlight['items'][1],
                 has_entries({
                     'slug': starts_with('slug'),
                     'title': 'title',
                     'dashboard-type': 'transaction',
                     'department': has_entries({
                         'title': starts_with('department'),
                         'abbr': starts_with('abbreviation')
                     }),
                     'agency': has_entries({
                         'title': starts_with('agency'),
                         'abbr': starts_with('abbreviation')
                     }),
                     'service': has_entries({
                         'title': starts_with('service'),
                         'abbr': starts_with('abbreviation')
                     })
                 }))
Example #47
0
    def test_list_dashboards_lists_dashboards(self):
        DashboardFactory(
            slug='dashboard',
            title='Dashboard',
            status='published'
        )
        resp = self.client.get(
            '/dashboards',
            HTTP_AUTHORIZATION='Bearer development-oauth-access-token')
        response_object = json.loads(resp.content)

        public_url = ('http://spotlight.dev.gov.uk/performance/dashboard')
        internal_url = ('http://stagecraft.dev.gov.uk/dashboard/')
        base_expectation = {
            'title': 'Dashboard',
            'public-url': public_url,
            'published': True,
        }

        assert_that(response_object[0], has_entries(base_expectation))
        assert_that(response_object[0], has_key('id'))
        assert_that(response_object[0]['url'], starts_with(internal_url))
Example #48
0
    def test_data_single_metric(self):
        sources = [["servers", "admin1", "loadavg", "01"]]
        start = 1391047920
        end = 1391048100

        with patch_urlopen() as mock_urlopen:
            mock_response = Mock()
            mock_response.read.return_value = """
            [
                {
                    "target": "servers.admin1.loadavg.01",
                    "datapoints": [
                        [2.0, 1391047920],
                        [6.0, 1391047980],
                        [9.0, 1391048040],
                        [null,1391048100]
                    ]
                }
            ]
            """
            mock_urlopen.return_value = mock_response
            result_json = self.ds.data(sources, start, end, width=100)

            expected_results = [
                {"t": 1391047920, "v": [2.0]},
                {"t": 1391047980, "v": [6.0]},
                {"t": 1391048040, "v": [9.0]},
                {"t": 1391048100, "v": [None]},
            ]

            result_list = json.loads(result_json)
            T.assert_equal(4, len(result_list))

            for i, expected_result in enumerate(expected_results):
                T.assert_dicts_equal(expected_result, result_list[i])

            mock_urlopen.assert_called_with(match(starts_with("http://dontcare.com:8080/render")))
            mock_urlopen.assert_called_with(match(contains_string(".".join(sources[0]))))
 def select_identity(self, name):
     self.is_active()
     self.results_list.select_item(with_item_text(starts_with(name)))
Example #50
0
 def assert_device_has_autoprov_config(self, device):
     assert_that(device[u'config'], starts_with(u'autoprov'))
Example #51
0
def external_hostname_is_not_local(provider):
    with provider.start(_IMAGE_NAME) as machine:
        hostname = machine.external_hostname()
        assert_that(hostname, hamcrest.is_not(hamcrest.equal_to("localhost")))
        assert_that(hostname, hamcrest.is_not(hamcrest.starts_with("127")))
Example #52
0
 def test_gives_a_graph_representation_of_itself(self):
     start = self.build_workflow_def()
     g = StringIO()
     start.write_graph(g)
     assert_that(g.getvalue(), starts_with("digraph Test"))
Example #53
0
    def test_connect_timeout(self):
        with self.assertRaises(ConnectTimeout) as expect:
            self.client("10.0.0.0", "whatever", "whatever", connect_timeout=1)

        assert_that(str(expect.exception), starts_with("Timed out while connecting to 10.0.0.0 on port"))
Example #54
0
 def test_get_type_fields(self):
     t = UnityType(_id='type')
     assert_that(t.fields_str, starts_with(
         'name,description,documentation,type,attributes.name'))
Example #55
0
 def test_get_minute_folders(self):
     folders = list(get_minute_folders('root'))
     for folder in folders:
         assert_that(folder, starts_with('root'))
         assert_that(folder, ends_with('minline'))
Example #56
0
 def test_fields_str(self):
     t = UnityType(_id='lun', cli=t_rest())
     assert_that(t.fields_str, starts_with('auSize,creationTime,'))
 def test_should_pass_username_to_dispatcher(self):
     service = ServiceBase(mvip="127.0.0.1",
                           api_version=9.0,
                           username="******")
     assert_that(service._dispatcher._credentials,
                 starts_with("fake_username"))