Custom Search

Friday, January 3, 2014

Openstack Project Python Keystoneclient Unit Test Tutorial Part1

1)
First go through following Doc
https://github.com/gabrielfalcao/HTTPretty

Try to understand following things
a)
@httpretty.activate

b)
httpretty.register_uri()
c)
requests.get()
requests.post()

d)
response.text
response.json()

e)
httpretty.last_request()


2)
Important Files


A)
./keystoneclient/tests/utils.py


import testtools

class TestCase(testtools.TestCase):
    TEST_DOMAIN_ID = '1'
    TEST_DOMAIN_NAME = 'aDomain'
    TEST_TENANT_ID = '1'
    TEST_TENANT_NAME = 'aTenant'
    TEST_TOKEN = 'aToken'
    TEST_TRUST_ID = 'aTrust'
    TEST_USER = 'test'
    TEST_ROOT_URL = 'http://127.0.0.1:5000/'

    def setUp(self):
        super(TestCase, self).setUp()

    def tearDown(self):
        super(TestCase, self).tearDown()

    def stub_url(self, method, parts=None, base_url=None, json=None, **kwargs):
    httpretty.register_uri(method, url, **kwargs)

    def assertRequestBodyIs(self, body=None, json=None):

    def assertRequestHeaderEqual(self, name, val):


B)
./keystoneclient/tests/v3/utils.py


from keystoneclient.tests import utils
from keystoneclient.v3 import client


class UnauthenticatedTestCase(utils.TestCase):

    """Class used as base for unauthenticated calls."""
    TEST_ROOT_URL = 'http://127.0.0.1:5000/'
    TEST_URL = '%s%s' % (TEST_ROOT_URL, 'v3')
    TEST_ROOT_ADMIN_URL = 'http://127.0.0.1:35357/'
    TEST_ADMIN_URL = '%s%s' % (TEST_ROOT_ADMIN_URL, 'v3')

class TestCase(UnauthenticatedTestCase):
    TEST_ADMIN_IDENTITY_ENDPOINT = "http://127.0.0.1:35357/v3"

    def setUp(self):
        super(TestCase, self).setUp()
        self.client = client.Client(username=self.TEST_USER,
                                    token=self.TEST_TOKEN,
                                    tenant_name=self.TEST_TENANT_NAME,
                                    auth_url=self.TEST_URL,
                                    endpoint=self.TEST_URL)


    def stub_auth(self, subject_token=None, **kwargs):
        if not subject_token:
            subject_token = self.TEST_TOKEN
        self.stub_url(httpretty.POST, ['auth', 'tokens'],
                      X_Subject_Token=subject_token, **kwargs)



class CrudTests(object):
    key = None
    collection_key = None
    model = None
    manager = None
    path_prefix = None

    def new_ref(self, **kwargs):
        kwargs.setdefault('id', uuid.uuid4().hex)
        return kwargs

    def stub_entity(self, method, parts=None, entity=None, id=None, **kwargs):
        if entity:
            entity = self.encode(entity)
            kwargs['json'] = entity

        if not parts:
            parts = [self.collection_key]

            if self.path_prefix:
                parts.insert(0, self.path_prefix)

        if id:
            if not parts:
                parts = []

            parts.append(id)

        self.stub_url(method, parts=parts, **kwargs)

    @httpretty.activate
    def test_create(self, ref=None, req_ref=None):

        ref = ref or self.new_ref()
        manager_ref = ref.copy()
        manager_ref.pop('id')

        # req_ref argument allows you to specify a different
        # signature for the request when the manager does some
        # conversion before doing the request (e.g converting
        # from datetime object to timestamp string)
        req_ref = req_ref or ref.copy()
        req_ref.pop('id')

        self.stub_entity(httpretty.POST, entity=req_ref, status=201)

        returned = self.manager.create(**parameterize(manager_ref))
        self.assertTrue(isinstance(returned, self.model))
        for attr in req_ref:
            self.assertEqual(
                getattr(returned, attr),
                req_ref[attr],
                'Expected different %s' % attr)
        self.assertEntityRequestBodyIs(req_ref)

C)
./keystoneclient/tests/v3/test_users.py


from keystoneclient.v3 import users
from keystoneclient.tests.v3 import utils

class UserTests(utils.TestCase, utils.CrudTests):
    def setUp(self):

        super(UserTests, self).setUp()
        self.key = 'user'
        self.collection_key = 'users'
        self.model = users.User
        self.manager = self.client.users

    def new_ref(self, **kwargs):
        kwargs = super(UserTests, self).new_ref(**kwargs)
        kwargs.setdefault('description', uuid.uuid4().hex)
        kwargs.setdefault('domain_id', uuid.uuid4().hex)
        kwargs.setdefault('enabled', True)
        kwargs.setdefault('name', uuid.uuid4().hex)
        kwargs.setdefault('default_project_id', uuid.uuid4().hex)
        return kwargs

    @httpretty.activate
    def test_add_user_to_group(self):

        group_id = uuid.uuid4().hex
        ref = self.new_ref()
        self.stub_url(httpretty.PUT,
                      ['groups', group_id, self.collection_key, ref['id']],
                      status=204)


        self.manager.add_to_group(user=ref['id'], group=group_id)
        self.assertRaises(exceptions.ValidationError,
                          self.manager.remove_from_group,
                          user=ref['id'],
                          group=None)

Part 2 ....

No comments:

Post a Comment