Beispiel #1
0
class ContentViewUpdateTestCase(APITestCase):
    """Tests for updating content views."""
    @classmethod
    def setUpClass(cls):  # noqa
        """Create a content view."""
        cls.content_view = entities.ContentView(
            id=entities.ContentView().create()['id'])

    @data(
        {u'name': entities.ContentView.name.gen_value()},
        {u'description': entities.ContentView.description.gen_value()},
    )
    def test_positive_update(self, attrs):
        """@Test: Update a content view and provide valid attributes.

        @Assert: The update succeeds.

        @Feature: ContentView

        """
        client.put(
            self.content_view.path(),
            attrs,
            auth=get_server_credentials(),
            verify=False,
        ).raise_for_status()

        # Read the content view and validate its attributes.
        new_attrs = self.content_view.read_json()
        for name, value in attrs.items():
            self.assertIn(name, new_attrs.keys())
            self.assertEqual(new_attrs[name], value)

    @data(
        {
            u'label': gen_utf8(30),
            u'bz-bug': 1147100
        },  # Immutable.
        {u'name': gen_utf8(256)},
    )
    def test_negative_update_1(self, attrs):
        """@Test: Update a content view and provide an invalid attribute.

        @Assert: The content view's attributes are not updated.

        @Feature: ContentView

        """
        bug_id = attrs.pop('bz-bug', None)
        if bug_id is not None and bz_bug_is_open(bug_id):
            self.skipTest('Bugzilla bug {0} is open.'.format(bug_id))

        response = client.put(
            self.content_view.path(),
            attrs,
            auth=get_server_credentials(),
            verify=False,
        )
        with self.assertRaises(HTTPError):
            response.raise_for_status()
    def test_bz_1114640(self):
        """@Test: Create a parameter for operating system 1.

        @Assert: A parameter is created and can be read afterwards.

        @Feature: OperatingSystemParameter

        """
        # Check whether OS 1 exists.
        entities.OperatingSystem(id=1).read_json()

        # Create and read a parameter for operating system 1. The purpose of
        # this test is to make sure an HTTP 422 is not returned, but we're also
        # going to verify the name and value of the parameter, just for good
        # measure.
        name = gen_utf8(20)
        value = gen_utf8(20)
        osp_id = entities.OperatingSystemParameter(
            1,
            name=name,
            value=value,
        ).create()['id']
        attrs = entities.OperatingSystemParameter(1, id=osp_id).read_json()
        self.assertEqual(attrs['name'], name)
        self.assertEqual(attrs['value'], value)
    def test_bz_1114640(self):
        """@Test: Create a parameter for operating system 1.

        @Assert: A parameter is created and can be read afterwards.

        @Feature: OperatingSystemParameter

        """
        # Check whether OS 1 exists.
        if (entities.OperatingSystem(id=1).read_raw().status_code == NOT_FOUND
                and entities.OperatingSystem().create_json()['id'] != 1):
            self.skipTest(
                'Cannot execute test, as operating system 1 is not available.'
            )

        # Create and read a parameter for operating system 1. The purpose of
        # this test is to make sure an HTTP 422 is not returned, but we're also
        # going to verify the name and value of the parameter, just for good
        # measure.
        name = gen_utf8(20)
        value = gen_utf8(20)
        osp_id = entities.OperatingSystemParameter(
            name=name,
            operatingsystem=1,
            value=value,
        ).create()['id']
        attrs = entities.OperatingSystemParameter(
            id=osp_id,
            operatingsystem=1,
        ).read_json()
        self.assertEqual(attrs['name'], name)
        self.assertEqual(attrs['value'], value)
    def test_positive_update_attributes(self):
        """Update a content view and provide valid attributes.

        @id: 3f1457f2-586b-472c-8053-99017c4a4909

        @Assert: The update succeeds.
        """
        attrs = {'description': gen_utf8(), 'name': gen_utf8()}
        for key, value in attrs.items():
            with self.subTest((key, value)):
                setattr(self.content_view, key, value)
                self.content_view = self.content_view.update({key})
                self.assertEqual(getattr(self.content_view, key), value)
Beispiel #5
0
    def test_positive_update_attributes(self):
        """@Test: Update a content view and provide valid attributes.

        @Assert: The update succeeds.

        @Feature: ContentView
        """
        attrs = {'description': gen_utf8(), 'name': gen_utf8()}
        for key, value in attrs.items():
            with self.subTest((key, value)):
                setattr(self.content_view, key, value)
                self.content_view = self.content_view.update({key})
                self.assertEqual(getattr(self.content_view, key), value)
    def test_positive_update_attributes(self):
        """Update a content view and provide valid attributes.

        @Assert: The update succeeds.

        @Feature: ContentView
        """
        attrs = {'description': gen_utf8(), 'name': gen_utf8()}
        for key, value in attrs.items():
            with self.subTest((key, value)):
                setattr(self.content_view, key, value)
                self.content_view = self.content_view.update({key})
                self.assertEqual(getattr(self.content_view, key), value)
Beispiel #7
0
    def test_negative_update_attributes(self):
        """@Test: Update a content view and provide an invalid attribute.

        @Assert: The content view's attributes are not updated.

        @Feature: ContentView
        """
        attrs = {'label': gen_utf8(30), 'name': gen_utf8(256)}
        for key, value in attrs.items():
            with self.subTest((key, value)):
                if key == 'label' and bz_bug_is_open(1147100):
                    continue
                setattr(self.content_view, key, value)
                with self.assertRaises(HTTPError):
                    self.content_view.update({key})
Beispiel #8
0
    def test_positive_post_hash(self):
        """Do not wrap API calls in an extra hash.

        @Assert: It is possible to associate an activation key with an
        organization.

        @Feature: Architecture
        """
        name = gen_utf8()
        os_id = entities.OperatingSystem().create_json()['id']
        response = client.post(
            entities.Architecture().path(),
            {
                u'name': name,
                u'operatingsystem_ids': [os_id]
            },
            auth=settings.server.get_credentials(),
            verify=False,
        )
        response.raise_for_status()
        attrs = response.json()

        # The server will accept some POSTed attributes (name) and silently
        # ignore others (operatingsystem_ids).
        self.assertIn('name', attrs)
        self.assertEqual(name, attrs['name'])
        self.assertIn('operatingsystems', attrs)
        self.assertEqual([os_id], attrs['operatingsystems'])
Beispiel #9
0
    def test_positive_post_hash(self):
        """Do not wrap API calls in an extra hash.

        @Assert: It is possible to associate an activation key with an
        organization.

        @Feature: Architecture
        """
        name = gen_utf8()
        os_id = entities.OperatingSystem().create_json()['id']
        response = client.post(
            entities.Architecture().path(),
            {u'name': name, u'operatingsystem_ids': [os_id]},
            auth=settings.server.get_credentials(),
            verify=False,
        )
        response.raise_for_status()
        attrs = response.json()

        # The server will accept some POSTed attributes (name) and silently
        # ignore others (operatingsystem_ids).
        self.assertIn('name', attrs)
        self.assertEqual(name, attrs['name'])
        self.assertIn('operatingsystems', attrs)
        self.assertEqual([os_id], attrs['operatingsystems'])
Beispiel #10
0
def test_positive_delete_with_user(session, module_org):
    """Delete a Usergroup that contains a user

    :id: 2bda3db5-f54f-412f-831f-8e005631f271

    :expectedresults: Usergroup is deleted but added user is not

    :CaseLevel: Integration
    """
    user_name = gen_string('alpha')
    group_name = gen_utf8(smp=False)
    # Create a new user
    entities.User(
        login=user_name,
        password=gen_string('alpha'),
        organization=[module_org],
    ).create()

    with session:
        session.usergroup.create({
            'usergroup.name': group_name,
            'usergroup.users': {
                'assigned': [user_name]
            },
        })
        session.usergroup.delete(group_name)
        assert not session.usergroup.search(group_name)
        assert session.user.search(user_name) is not None
def test_positive_delete_with_user(session, module_org, module_loc):
    """Delete a Usergroup that contains a user

    :id: 2bda3db5-f54f-412f-831f-8e005631f271

    :expectedresults: Usergroup is deleted but added user is not

    :CaseLevel: Integration
    """
    user_name = gen_string('alpha')
    group_name = gen_utf8(smp=False)
    # Create a new user
    entities.User(
        login=user_name,
        password=gen_string('alpha'),
        organization=[module_org],
        location=[module_loc]
    ).create()

    with session:
        session.usergroup.create({
            'usergroup.name': group_name,
            'usergroup.users': {'assigned': [user_name]},
        })
        session.usergroup.delete(group_name)
        assert not session.usergroup.search(group_name)
        assert session.user.search(user_name) is not None
Beispiel #12
0
class CategoryFactory(factory.Factory):
    """Provide a factory for randomized ``hamster_lib.Category`` instances."""

    pk = None
    name = fauxfactory.gen_utf8()

    class Meta:
        model = hamster_lib.Category
Beispiel #13
0
class ActivityFactory(factory.Factory):
    """Provide a factory for randomized ``hamster_lib.Activity`` instances."""

    pk = None
    name = fauxfactory.gen_utf8()
    category = factory.SubFactory(CategoryFactory)
    deleted = False

    class Meta:
        model = hamster_lib.Activity
    def test_negative_update_label(self):
        """Try to update a content view label with any value

        @id: 77883887-800f-412f-91a3-b2f7ed999c70

        @Assert: The content view label is immutable and cannot be modified
        """
        with self.assertRaises(HTTPError):
            entities.ContentView(
                id=self.content_view.id,
                label=gen_utf8(30)).update(['label'])
    def test_negative_update_label(self):
        """Try to update a content view label with any value

        @Assert: The content view label is immutable and cannot be modified

        @Feature: ContentView
        """
        with self.assertRaises(HTTPError):
            entities.ContentView(
                id=self.content_view.id,
                label=gen_utf8(30)).update(['label'])
Beispiel #16
0
    def test_negative_update_label(self):
        """Try to update a content view label with any value

        @Assert: The content view label is immutable and cannot be modified

        @Feature: ContentView
        """
        with self.assertRaises(HTTPError):
            entities.ContentView(
                id=self.content_view.id,
                label=gen_utf8(30)).update(['label'])
Beispiel #17
0
def test_positive_create_with_name(session):
    """Create new Usergroup using different names

    :expectedresults: Usergroup is created successfully

    :CaseImportance: Critical
    """
    group_name = gen_utf8(smp=False)
    with session:
        session.usergroup.create({
            'usergroup.name': group_name,
        })
        assert session.usergroup.search(group_name) is not None
 def id_generator(size=8, utf8=True):
     """
     Generates a random character string (Letters + Digits)
     Default length of string generated is 8
     Only considers ascii letters and digits
     """
     if utf8:
         alphasize = random.randint(1, size - 1)
         utfsize = size - alphasize
         result = fauxfactory.gen_alphanumeric(
             alphasize) + fauxfactory.gen_utf8(utfsize)
     else:
         result = fauxfactory.gen_alphanumeric(size)
     return result
Beispiel #19
0
def test_positive_delete_empty(session):
    """Delete an empty Usergroup

    :expectedresults: Usergroup is deleted

    :CaseImportance: Critical
    """
    group_name = gen_utf8(smp=False)
    with session:
        session.usergroup.create({
            'usergroup.name': group_name,
        })
        session.usergroup.delete(group_name)
        assert not session.usergroup.search(group_name)
Beispiel #20
0
def valid_domain_names(interface=None, length=None):
    """Valid domain names."""
    max_len = 255 - len(DOMAIN % '')
    if not length:
        length = random.randint(1, max_len)
    if length > max_len:
        raise ValueError('length is too large, max: {}'.format(max_len))
    names = {
        'alphanumeric': DOMAIN % gen_string('alphanumeric', length),
        'alpha': DOMAIN % gen_string('alpha', length),
        'numeric': DOMAIN % gen_string('numeric', length),
        'latin1': DOMAIN % gen_string('latin1', length),
        'utf8': DOMAIN % gen_utf8(length),
    }
    return names
Beispiel #21
0
def valid_domain_names(interface=None, length=None):
    """Valid domain names."""
    max_len = 255 - len(DOMAIN % '')
    if not length:
        length = random.randint(1, max_len)
    if length > max_len:
        raise ValueError('length is too large, max: {}'.format(max_len))
    names = {
        'alphanumeric': DOMAIN % gen_string('alphanumeric', length),
        'alpha': DOMAIN % gen_string('alpha', length),
        'numeric': DOMAIN % gen_string('numeric', length),
        'latin1': DOMAIN % gen_string('latin1', length),
        'utf8': DOMAIN % gen_utf8(length),
    }
    return names
Beispiel #22
0
def test_positive_update_name(session):
    """Update usergroup with new name

    :expectedresults: Usergroup is updated

    :CaseImportance: Critical
    """
    group_name = gen_string('alpha')
    new_group_name = gen_utf8(smp=False)
    with session:
        session.usergroup.create({
            'usergroup.name': group_name,
        })
        session.usergroup.update(group_name, {
            'usergroup.name': new_group_name,
        })
        assert session.usergroup.search(new_group_name) is not None
        assert not session.usergroup.search(group_name)
Beispiel #23
0
 def func_wrapper(*args, **kwargs):
     """Perform smoke test attribute check"""
     dataset = func(*args, **kwargs)
     if isinstance(dataset, dict):
         # New UI tests are written using pytest, update dict to support pytest's parametrize
         if 'ui' in args or kwargs.get('interface') == 'ui' and settings.webdriver == 'chrome':
             # Chromedriver only supports BMP chars
             utf8 = dataset.pop('utf8', None)
             if utf8:
                 dataset['utf8'] = gen_utf8(len(utf8), smp=False)
         if settings.run_one_datapoint:
             key = random.choice(list(dataset.keys()))
             dataset = {key: dataset[key]}
     else:
         # Otherwise use list for backwards compatibility
         dataset = list(dataset)
         if settings.run_one_datapoint:
             dataset = [random.choice(dataset)]
     return dataset
    def func_wrapper(*args, **kwargs):
        """Perform smoke test attribute check"""
        dataset = func(*args, **kwargs)
        if isinstance(dataset, dict):
            # New UI tests are written using pytest, update dict to support
            # pytest's parametrize
            if 'ui' in args or kwargs.get('interface') == 'ui':
                # Chromedriver only supports BMP chars
                if settings.webdriver == 'chrome':
                    utf8 = dataset.pop('utf8', None)
                    if utf8:
                        dataset['utf8'] = gen_utf8(len(utf8), smp=False)
                if settings.run_one_datapoint:
                    key = random.choice(list(dataset.keys()))
                    dataset = {key: dataset[key]}
                return xdist_adapter(dataset.values())
            # Otherwise use list for backwards compatibility
            dataset = list(dataset.values())

        if settings.run_one_datapoint:
            dataset = [random.choice(dataset)]
        return dataset
Beispiel #25
0
def filename():
    """Provide a filename string."""
    return fauxfactory.gen_utf8()
Beispiel #26
0
    datetime.time(5, 30, 0),
    datetime.time(17, 22, 0),
))
def day_start_parametrized(request):
    """Return a parametrized day_start value."""
    return request.param


@pytest.fixture(params=(0, 1, 30, 60))
def fact_min_delta_parametrized(request):
    """Return a parametrized fact_min_delta value."""
    return request.param


@pytest.fixture(params=(
    fauxfactory.gen_utf8(),
    fauxfactory.gen_latin1(),
))
def tmpfile_path_parametrized(request, tmpdir):
    """Return a parametrized tmpfile_path value."""
    return tmpdir.mkdir(request.param).join('tmpfile.hamster')


@pytest.fixture(params=(
    'sqlite',
))
def db_engine_parametrized(request):
    """Return a parametrized db_engine value."""
    return request.param

Beispiel #27
0
def filename():
    """Provide a filename string."""
    return fauxfactory.gen_utf8()
Beispiel #28
0
def db_password(request):
    """Return a randomized database password."""
    return fauxfactory.gen_utf8()
Beispiel #29
0
def db_user(request):
    """Return a randomized database username."""
    return fauxfactory.gen_utf8()
Beispiel #30
0
def name():
    """Randomized, valid but non-parametrized name string."""
    return fauxfactory.gen_utf8()
Beispiel #31
0
    Note:
        [Reference](http://factoryboy.readthedocs.org/en/latest/orms.html#sqlalchemy)
    """
    engine = create_engine('sqlite:///:memory:')
    objects.metadata.bind = engine
    objects.metadata.create_all(engine)
    common.Session.configure(bind=engine)

    def fin():
        common.Session.remove()

    request.addfinalizer(fin)


@pytest.fixture(params=[
    fauxfactory.gen_utf8(),
    fauxfactory.gen_alphanumeric(),
    ':memory:',
])
def db_path_parametrized(request, tmpdir):
    """Parametrized database paths."""
    if request.param == ':memory:':
        path = request.param
    else:
        path = os.path.join(tmpdir.strpath, request.param)
    return path


@pytest.fixture
def alchemy_config(request, base_config):
    """Provide a config that is suitable for sqlalchemy stores."""
Beispiel #32
0
def test_bmp_chars_only():
    """Unicode letters generator generates only BMP unicode letters."""
    for char in gen_utf8(length=50, smp=False):
        assert ord(char) <= BMP.max
Beispiel #33
0
def name():
    """Randomized, valid but non-parametrized name string."""
    return fauxfactory.gen_utf8()
Beispiel #34
0
@pytest.fixture
def fact_manager(request, live_service):
    """Provide a convenient object hook to our hamster-dbus service."""
    daemon, bus = live_service
    object_ = bus.get_object('org.projecthamster.HamsterDBus',
                             '/org/projecthamster/HamsterDBus/FactManager')
    interface = dbus.Interface(
        object_, dbus_interface='org.projecthamster.HamsterDBus.FactManager1')
    return interface


# Data
@pytest.fixture(params=[
    fauxfactory.gen_alpha(),
    fauxfactory.gen_utf8(),
    fauxfactory.gen_latin1(),
    fauxfactory.gen_cjk(),
])
def category_name_parametrized(request):
    """Provide a huge variety of possible ``Category.name`` strings."""
    return request.param


@pytest.fixture(params=[
    fauxfactory.gen_alpha(),
    fauxfactory.gen_utf8(),
    fauxfactory.gen_latin1(),
    fauxfactory.gen_cjk(),
])
def activity_name_parametrized(request):
Beispiel #35
0
    Note:
        [Reference](http://factoryboy.readthedocs.org/en/latest/orms.html#sqlalchemy)
    """
    engine = create_engine('sqlite:///:memory:')
    objects.metadata.bind = engine
    objects.metadata.create_all(engine)
    common.Session.configure(bind=engine)

    def fin():
        common.Session.remove()

    request.addfinalizer(fin)


@pytest.fixture(params=[
    fauxfactory.gen_utf8(),
    fauxfactory.gen_alphanumeric(),
    ':memory:',
])
def db_path_parametrized(request, tmpdir):
    """Parametrized database paths."""
    if request.param == ':memory:':
        path = request.param
    else:
        path = os.path.join(tmpdir.strpath, request.param)
    return path


@pytest.fixture
def alchemy_config(request, base_config):
    """Provide a config that is suitable for sqlalchemy stores."""