pytest-dev / pytest-django

A Django plugin for pytest.
https://pytest-django.readthedocs.io/
Other
1.37k stars 343 forks source link

django pytest doesn't show test db getting created #659

Closed py2k5 closed 5 years ago

py2k5 commented 5 years ago

When I run manage.py test it shows all migrations but if I run pytest it doesn't show any migrations. And also it looks like pytest is directly querying my database instead of test database as I run User.objects.get() and it gives me all users. My understanding that the test DBs are empty unless you feed data.

pytest -v output: platform linux -- Python 3.6.3, pytest-3.7.0, py-1.5.2, pluggy-0.7.1 -- /opt2/python3/bin/python3.6 cachedir: .pytest_cache rootdir: /opt2/home/pkro/nwsbase/nmsapi, inifile: pytest.ini plugins: cov-2.5.1, celery-4.2.1 collected 2 items

tests/portal/test_views.py::TestLocations::test_can_get_locations FAILED [ 50%] tests/portal/test_views.py::TestLocations::test_whoami PASSED

manage.py test output: python3 manage.py test Creating test database for alias 'default'... Creating test database for alias 'applications'... System check identified no issues (0 silenced).

blueyed commented 5 years ago

-vv should show it.

Also make sure to actually re-create the DB (--create-db - depending on your config).

Closing, assuming this to be answered.

Please consider updating the docs if you feel it is missing there somehow.

py2k5 commented 5 years ago

No, still doesn't show. I have pytest but I have a doubt that pytest-django plugin is missing

py2k5 commented 5 years ago

pytest --version This is pytest version 3.7.0, imported from /opt2/python3/lib/python3.6/site-packages/pytest.py setuptools registered plugins: pytest-cov-2.5.1 at /opt2/python3/lib/python3.6/site-packages/pytest_cov/plugin.py celery-4.2.1 at /opt2/python3/lib/python3.6/site-packages/celery/contrib/pytest.py

blueyed commented 5 years ago

plugins: cov-2.5.1, celery-4.2.1

Indeed.

blueyed commented 5 years ago

Above you had a different Python version also:

platform linux -- Python 3.6.3, pytest-3.7.0, py-1.5.2, pluggy-0.7.1 -- /opt2/python3/bin/python3.6

I suggest using a virtualenv: python -m venv .venv && PATH=$PWD/.venv/bin:$PATH

py2k5 commented 5 years ago

I just installed pytest-django plugin and it starts creating the test db now. However, I still have permission problem. I created a testuser but it can not run my APIs. I am using APIClient from rest_framework.test. Do I need to provide some permissions to the testuser I created and what are the commands for that please?

blueyed commented 5 years ago

Check out http://www.django-rest-framework.org/api-guide/testing/#authenticating. But you also need to ensure there is a user, of course. How did you create the testuser? In the prod/non-test DB? The testing DB is separate, and you need to create users there (e.g. through pytest fixtures).

blueyed commented 5 years ago

pytest-django provides a convenient admin_user fixture: https://github.com/blueyed/pytest-django/blob/23d1ce2953413fe3d945a5f5051faed7e74ce986/pytest_django/fixtures.py#L232-L250

py2k5 commented 5 years ago

I created a simple user like below self.user = User.objects.create_user(username='testuser') self.user.set_password('12345') self.user.save() self.client.login(username='testuser', password='12345'

py2k5 commented 5 years ago

Regarding the admin_user fixture, I am not too clear of it use. Is there any example of its usage.

blueyed commented 5 years ago

See https://pytest-django.readthedocs.io/en/latest/helpers.html?highlight=admin_user#admin-user-an-admin-user-superuser.

You would use it in a test like this:

def test_foo(client, admin_user):
    client.force_login(admin_user)
    client.get(…)

There is also https://pytest-django.readthedocs.io/en/latest/helpers.html?highlight=admin_user#admin-client-django-test-client-logged-in-as-admin though, so you use admin_client directly.

This is not a APIClient though.

But enough for off-topic here I guess.. :)

py2k5 commented 5 years ago

Ok I will check. Can a regular django Client can do API tests ? I am using APIClient in my tests.

blueyed commented 5 years ago

Sure, it's just not as convenient. Typically you will create specialized fixtures tied to your needs anyway based on them.

py2k5 commented 5 years ago

No matter what I do I run into some or other problem. I have 4 databases installed and the API I am testing is using a different DB than default. It gives an error like django.db.utils.ProgrammingError: (1146, "Table 'test_nmportal.locations' doesn't exist") . Any help please?

blueyed commented 5 years ago

Can you display the run with -vv? And your database settings?

py2k5 commented 5 years ago

DB settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nmsapi', 'USER': db_user, 'PASSWORD': db_pass, 'HOST': 'XXXX', }, 'nmportal': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nmportal', 'USER': db_user, 'PASSWORD': db_pass, 'HOST': 'XXXX' }, 'applications': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'applications', 'USER': db_user, 'PASSWORD': db_pass, 'HOST': 'XXXX' }, 'nmisdb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nmisdb', 'USER': db_user, 'PASSWORD': db_pass, 'HOST': 'XXXX' } }

output:

pytest -vv ============================================================================================================================================= test session starts ============================================================================================================================================== platform linux -- Python 3.6.3, pytest-3.7.0, py-1.5.2, pluggy-0.7.1 -- /opt2/python3/bin/python3.6 cachedir: .pytest_cache Django settings: nmsapi.settings_dev (from environment variable) rootdir: /opt2/home/pkro/nwsbase/nmsapi, inifile: pytest.ini plugins: django-3.4.3, cov-2.5.1, celery-4.2.1 collected 3 items

tests/portal/test_views.py::TestLocations::test_can_get_locations FAILED [ 33%] tests/portal/test_views.py::TestLocations::test_job_creation FAILED [ 66%] tests/portal/test_views.py::TestLocations::test_whoami PASSED [100%]

=================================================================================================================================================== FAILURES =================================================================================================================================================== _____ TestLocations.test_can_getlocations ____

self = <django.db.backends.utils.CursorWrapper object at 0x7f2fe7cae748>, sql = 'SELECT COUNT(*) AS __count FROM locations', params = () ignored_wrapper_args = (False, {'connection': <django.db.backends.mysql.base.DatabaseWrapper object at 0x7f2ff3e5d320>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7f2fe7cae748>})

def _execute(self, sql, params, *ignored_wrapper_args):
    self.db.validate_no_broken_transaction()
    with self.db.wrap_database_errors:
        if params is None:
            return self.cursor.execute(sql)
        else:
          return self.cursor.execute(sql, params)

/opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py:85:


self = <django.db.backends.mysql.base.CursorWrapper object at 0x7f2fe7cae710>, query = 'SELECT COUNT(*) AS __count FROM locations', args = ()

def execute(self, query, args=None):
    try:
        # args is None means no string interpolation
      return self.cursor.execute(query, args)

/opt2/python3/lib/python3.6/site-packages/django/db/backends/mysql/base.py:71:


self = <MySQLdb.cursors.Cursor object at 0x7f2fe7cae6a0>, query = b'SELECT COUNT(*) AS __count FROM locations', args = ()

def execute(self, query, args=None):
    """Execute a query.

        query -- string, query to execute on server
        args -- optional sequence or mapping, parameters to use with query.

        Note: If args is a sequence, then %s must be used as the
        parameter placeholder in the query. If a mapping is used,
        %(key)s must be used as the placeholder.

        Returns integer represents rows affected, if any
        """
    while self.nextset():
        pass
    db = self._get_db()

    # NOTE:
    # Python 2: query should be bytes when executing %.
    # All unicode in args should be encoded to bytes on Python 2.
    # Python 3: query should be str (unicode) when executing %.
    # All bytes in args should be decoded with ascii and surrogateescape on Python 3.
    # db.literal(obj) always returns str.

    if PY2 and isinstance(query, unicode):
        query = query.encode(db.encoding)

    if args is not None:
        if isinstance(args, dict):
            args = dict((key, db.literal(item)) for key, item in args.items())
        else:
            args = tuple(map(db.literal, args))
        if not PY2 and isinstance(query, (bytes, bytearray)):
            query = query.decode(db.encoding)
        try:
            query = query % args
        except TypeError as m:
            self.errorhandler(self, ProgrammingError, str(m))

    if isinstance(query, unicode):
        query = query.encode(db.encoding, 'surrogateescape')

    res = None
    try:
        res = self._query(query)
    except Exception:
        exc, value = sys.exc_info()[:2]
      self.errorhandler(self, exc, value)

/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py:250:


errorclass = <class '_mysql_exceptions.ProgrammingError'>, errorvalue = ProgrammingError(1146, "Table 'test_nmportal.locations' doesn't exist")

def defaulterrorhandler(connection, cursor, errorclass, errorvalue):
    """
    If cursor is not None, (errorclass, errorvalue) is appended to
    cursor.messages; otherwise it is appended to
    connection.messages. Then errorclass is raised with errorvalue as
    the value.

    You can override this with your own error handler by assigning it
    to the instance.
    """
    error = errorclass, errorvalue
    if cursor:
        cursor.messages.append(error)
    else:
        connection.messages.append(error)
    del cursor
    del connection
    if isinstance(errorvalue, BaseException):
      raise errorvalue

/opt2/python3/lib/python3.6/site-packages/MySQLdb/connections.py:50:


self = <MySQLdb.cursors.Cursor object at 0x7f2fe7cae6a0>, query = b'SELECT COUNT(*) AS __count FROM locations', args = ()

def execute(self, query, args=None):
    """Execute a query.

        query -- string, query to execute on server
        args -- optional sequence or mapping, parameters to use with query.

        Note: If args is a sequence, then %s must be used as the
        parameter placeholder in the query. If a mapping is used,
        %(key)s must be used as the placeholder.

        Returns integer represents rows affected, if any
        """
    while self.nextset():
        pass
    db = self._get_db()

    # NOTE:
    # Python 2: query should be bytes when executing %.
    # All unicode in args should be encoded to bytes on Python 2.
    # Python 3: query should be str (unicode) when executing %.
    # All bytes in args should be decoded with ascii and surrogateescape on Python 3.
    # db.literal(obj) always returns str.

    if PY2 and isinstance(query, unicode):
        query = query.encode(db.encoding)

    if args is not None:
        if isinstance(args, dict):
            args = dict((key, db.literal(item)) for key, item in args.items())
        else:
            args = tuple(map(db.literal, args))
        if not PY2 and isinstance(query, (bytes, bytearray)):
            query = query.decode(db.encoding)
        try:
            query = query % args
        except TypeError as m:
            self.errorhandler(self, ProgrammingError, str(m))

    if isinstance(query, unicode):
        query = query.encode(db.encoding, 'surrogateescape')

    res = None
    try:
      res = self._query(query)

/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py:247:


self = <MySQLdb.cursors.Cursor object at 0x7f2fe7cae6a0>, q = b'SELECT COUNT(*) AS __count FROM locations'

def _query(self, q):
  rowcount = self._do_query(q)

/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py:411:


self = <MySQLdb.cursors.Cursor object at 0x7f2fe7cae6a0>, q = b'SELECT COUNT(*) AS __count FROM locations'

def _do_query(self, q):
    db = self._get_db()
    self._last_executed = q
  db.query(q)

/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py:374:


self = <_mysql.connection open to 'nms-db-dev.macbank' at 264e0a8>, query = b'SELECT COUNT(*) AS __count FROM locations'

def query(self, query):
    # Since _mysql releases GIL while querying, we need immutable buffer.
    if isinstance(query, bytearray):
        query = bytes(query)
    if self.waiter is not None:
        self.send_query(query)
        self.waiter(self.fileno())
        self.read_query_result()
    else:
      _mysql.connection.query(self, query)

E _mysql_exceptions.ProgrammingError: (1146, "Table 'test_nmportal.locations' doesn't exist")

/opt2/python3/lib/python3.6/site-packages/MySQLdb/connections.py:277: ProgrammingError

The above exception was the direct cause of the following exception:

self =

def test_can_get_locations(self):

    #url = reverse('hardware-list')
    #response = self.client.get('/ace/jobs/')
  response = self.client.get('/locations/')

tests/portal/test_views.py:106:


/opt2/python3/lib/python3.6/site-packages/rest_framework/test.py:292: in get response = super(APIClient, self).get(path, data=data, extra) /opt2/python3/lib/python3.6/site-packages/rest_framework/test.py:209: in get return self.generic('GET', path, r) /opt2/python3/lib/python3.6/site-packages/rest_framework/test.py:238: in generic method, path, data, content_type, secure, extra) /opt2/python3/lib/python3.6/site-packages/django/test/client.py:414: in generic return self.request(r) /opt2/python3/lib/python3.6/site-packages/rest_framework/test.py:289: in request return super(APIClient, self).request(kwargs) /opt2/python3/lib/python3.6/site-packages/rest_framework/test.py:241: in request request = super(APIRequestFactory, self).request(kwargs) /opt2/python3/lib/python3.6/site-packages/django/test/client.py:495: in request raise exc_value /opt2/python3/lib/python3.6/site-packages/django/core/handlers/exception.py:34: in inner response = get_response(request) /opt2/python3/lib/python3.6/site-packages/django/core/handlers/base.py:126: in _get_response response = self.process_exception_by_middleware(e, request) /opt2/python3/lib/python3.6/site-packages/django/core/handlers/base.py:124: in _get_response response = wrapped_callback(request, *callback_args, callback_kwargs) /opt2/python3/lib/python3.6/site-packages/django/views/decorators/csrf.py:54: in wrapped_view return view_func(*args, *kwargs) /opt2/python3/lib/python3.6/site-packages/rest_framework/viewsets.py:103: in view return self.dispatch(request, args, kwargs) /opt2/python3/lib/python3.6/site-packages/rest_framework/views.py:483: in dispatch response = self.handle_exception(exc) mixins/LoggingMixin.py:94: in handle_exception response = super(LoggingMixin, self).handle_exception(exc) /opt2/python3/lib/python3.6/site-packages/rest_framework/views.py:443: in handle_exception self.raise_uncaught_exception(exc) /opt2/python3/lib/python3.6/site-packages/rest_framework/views.py:480: in dispatch response = handler(request, *args, **kwargs) nmp/views/Locations.py:57: in list page = self.paginate_queryset(queryset) /opt2/python3/lib/python3.6/site-packages/rest_framework/generics.py:173: in paginate_queryset return self.paginator.paginate_queryset(queryset, self.request, view=self) /opt2/python3/lib/python3.6/site-packages/rest_framework/pagination.py:204: in paginate_queryset self.page = paginator.page(page_number) /opt2/python3/lib/python3.6/site-packages/django/core/paginator.py:67: in page number = self.validate_number(number) /opt2/python3/lib/python3.6/site-packages/django/core/paginator.py:45: in validate_number if number > self.num_pages: /opt2/python3/lib/python3.6/site-packages/django/utils/functional.py:37: in get res = instance.dict[self.name] = self.func(instance) /opt2/python3/lib/python3.6/site-packages/django/core/paginator.py:97: in num_pages if self.count == 0 and not self.allow_empty_first_page: /opt2/python3/lib/python3.6/site-packages/django/utils/functional.py:37: in get res = instance.dict[self.name] = self.func(instance) /opt2/python3/lib/python3.6/site-packages/django/core/paginator.py:87: in count return self.object_list.count() /opt2/python3/lib/python3.6/site-packages/django/db/models/query.py:383: in count return self.query.get_count(using=self.db) /opt2/python3/lib/python3.6/site-packages/django/db/models/sql/query.py:498: in get_count number = obj.get_aggregation(using, ['count'])['count'] /opt2/python3/lib/python3.6/site-packages/django/db/models/sql/query.py:483: in get_aggregation result = compiler.execute_sql(SINGLE) /opt2/python3/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1065: in execute_sql cursor.execute(sql, params) /opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py:68: in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) /opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py:77: in _execute_with_wrappers return executor(sql, params, many, context) /opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py:85: in _execute return self.cursor.execute(sql, params) /opt2/python3/lib/python3.6/site-packages/django/db/utils.py:89: in exit raise dj_exc_value.with_traceback(traceback) from exc_value /opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py:85: in _execute return self.cursor.execute(sql, params) /opt2/python3/lib/python3.6/site-packages/django/db/backends/mysql/base.py:71: in execute return self.cursor.execute(query, args) /opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py:250: in execute self.errorhandler(self, exc, value) /opt2/python3/lib/python3.6/site-packages/MySQLdb/connections.py:50: in defaulterrorhandler raise errorvalue /opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py:247: in execute res = self._query(query) /opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py:411: in _query rowcount = self._do_query(q) /opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py:374: in _do_query db.query(q)


self = <_mysql.connection open to 'nms-db-dev.macbank' at 264e0a8>, query = b'SELECT COUNT(*) AS __count FROM locations'

def query(self, query):
    # Since _mysql releases GIL while querying, we need immutable buffer.
    if isinstance(query, bytearray):
        query = bytes(query)
    if self.waiter is not None:
        self.send_query(query)
        self.waiter(self.fileno())
        self.read_query_result()
    else:
      _mysql.connection.query(self, query)

E django.db.utils.ProgrammingError: (1146, "Table 'test_nmportal.locations' doesn't exist")

/opt2/python3/lib/python3.6/site-packages/MySQLdb/connections.py:277: ProgrammingError -------------------------------------------------------------------------------------------------------------------------------------------- Captured stdout setup --------------------------------------------------------------------------------------------------------------------------------------------- Creating test database for alias 'default' ('test_nmsapi')... Operations to perform: Synchronize unmigrated apps: corsheaders, messages, nwsrequests, rest_framework, rest_framework_filters, rest_framework_swagger, staticfiles Apply all migrations: ace, admin, auth, compliance, contenttypes, core, nmis, nmp, nms, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying ace.0001_initial... OK Applying ace.0002_auto_20180921_0057... OK Applying ace.0003_auto_20180921_0058... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying compliance.0001_initial... OK Applying core.0001_initial... OK Applying nmis.0001_initial... OK Applying nmp.0001_initial... OK Applying nms.0001_initial... OK Applying sessions.0001_initial... OK Creating test database for alias 'nmportal' ('test_nmportal')... Operations to perform: Synchronize unmigrated apps: corsheaders, messages, nwsrequests, rest_framework, rest_framework_filters, rest_framework_swagger, staticfiles Apply all migrations: ace, admin, auth, compliance, contenttypes, core, nmis, nmp, nms, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying ace.0001_initial... OK Applying ace.0002_auto_20180921_0057... OK Applying ace.0003_auto_20180921_0058... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying compliance.0001_initial... OK Applying core.0001_initial... OK Applying nmis.0001_initial... OK Applying nmp.0001_initial... OK Applying nms.0001_initial... OK Applying sessions.0001_initial... OK Creating test database for alias 'applications' ('test_applications')... Operations to perform: Synchronize unmigrated apps: corsheaders, messages, nwsrequests, rest_framework, rest_framework_filters, rest_framework_swagger, staticfiles Apply all migrations: ace, admin, auth, compliance, contenttypes, core, nmis, nmp, nms, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying ace.0001_initial... OK Applying ace.0002_auto_20180921_0057... OK Applying ace.0003_auto_20180921_0058... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying compliance.0001_initial... OK Applying core.0001_initial... OK Applying nmis.0001_initial... OK Applying nmp.0001_initial... OK Applying nms.0001_initial... OK Applying sessions.0001_initial... OK Creating test database for alias 'nmisdb' ('test_nmisdb')... Operations to perform: Synchronize unmigrated apps: corsheaders, messages, nwsrequests, rest_framework, rest_framework_filters, rest_framework_swagger, staticfiles Apply all migrations: ace, admin, auth, compliance, contenttypes, core, nmis, nmp, nms, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying ace.0001_initial... OK Applying ace.0002_auto_20180921_0057... OK Applying ace.0003_auto_20180921_0058... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying compliance.0001_initial... OK Applying core.0001_initial... OK Applying nmis.0001_initial... OK Applying nmp.0001_initial... OK Applying nms.0001_initial... OK Applying sessions.0001_initial... OK --------------------------------------------------------------------------------------------------------------------------------------------- Captured stdout call --------------------------------------------------------------------------------------------------------------------------------------------- testuser 2018-09-25 01:12:06,609,usydind10018,django.request,log_response,Line=228,PID=25757,ERROR,Internal Server Error: /locations/ Traceback (most recent call last): File "/opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/opt2/python3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.ProgrammingError: (1146, "Table 'test_nmportal.locations' doesn't exist")

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "/opt2/python3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt2/python3/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt2/python3/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, callback_kwargs) File "/opt2/python3/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, *kwargs) File "/opt2/python3/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view return self.dispatch(request, args, kwargs) File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/opt2/home/pkro/nwsbase/nmsapi/mixins/LoggingMixin.py", line 94, in handle_exception response = super(LoggingMixin, self).handle_exception(exc) File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/opt2/home/pkro/nwsbase/nmsapi/nmp/views/Locations.py", line 57, in list page = self.paginate_queryset(queryset) File "/opt2/python3/lib/python3.6/site-packages/rest_framework/generics.py", line 173, in paginate_queryset return self.paginator.paginate_queryset(queryset, self.request, view=self) File "/opt2/python3/lib/python3.6/site-packages/rest_framework/pagination.py", line 204, in paginate_queryset self.page = paginator.page(page_number) File "/opt2/python3/lib/python3.6/site-packages/django/core/paginator.py", line 67, in page number = self.validate_number(number) File "/opt2/python3/lib/python3.6/site-packages/django/core/paginator.py", line 45, in validate_number if number > self.num_pages: File "/opt2/python3/lib/python3.6/site-packages/django/utils/functional.py", line 37, in get res = instance.dict[self.name] = self.func(instance) File "/opt2/python3/lib/python3.6/site-packages/django/core/paginator.py", line 97, in num_pages if self.count == 0 and not self.allow_empty_first_page: File "/opt2/python3/lib/python3.6/site-packages/django/utils/functional.py", line 37, in get res = instance.dict[self.name] = self.func(instance) File "/opt2/python3/lib/python3.6/site-packages/django/core/paginator.py", line 87, in count return self.object_list.count() File "/opt2/python3/lib/python3.6/site-packages/django/db/models/query.py", line 383, in count return self.query.get_count(using=self.db) File "/opt2/python3/lib/python3.6/site-packages/django/db/models/sql/query.py", line 498, in get_count number = obj.get_aggregation(using, ['count'])['count'] File "/opt2/python3/lib/python3.6/site-packages/django/db/models/sql/query.py", line 483, in get_aggregation result = compiler.execute_sql(SINGLE) File "/opt2/python3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1065, in execute_sql cursor.execute(sql, params) File "/opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/opt2/python3/lib/python3.6/site-packages/django/db/utils.py", line 89, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/opt2/python3/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/opt2/python3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/opt2/python3/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1146, "Table 'test_nmportal.locations' doesn't exist") ___ TestLocations.test_job_creation ____

self =

def test_job_creation(self):
    job_object = {"job_name": "Unit test from framework", "job_description": "test description",
                  "job_code": "PRODUCTIONISE_DEVICE", "created_by": "username", "status": "Precheck Pending",
                  "job_settings": {"job_name": "Unit test from framework", "job_description": "test description",
                                   "devices": "sss-lab-nws1", "save_flash": False, "command_collection": False,
                                   "override_version": "", "override_RAT": ""}}

    response = self.client.post('/ace/jobs/', job_object, format='json', type='application/json')
  self.assertEqual(response.status_code, status.HTTP_201_CREATED, "output= {}".format(response))

E AssertionError: 403 != 201 : output= <Response status_code=403, "application/json">

tests/portal/test_views.py:122: AssertionError --------------------------------------------------------------------------------------------------------------------------------------------- Captured stdout call --------------------------------------------------------------------------------------------------------------------------------------------- testuser 2018-09-25 01:12:07,978,usydind10018,django_auth_ldap,_populate_user_from_attributes,Line=656,PID=25757,WARNING,cn=testuser,dc=pc,dc=internal,dc=macquarie,dc=com does not have a value for the attribute sn 2018-09-25 01:12:07,979,usydind10018,django_auth_ldap,_populate_user_from_attributes,Line=656,PID=25757,WARNING,cn=testuser,dc=pc,dc=internal,dc=macquarie,dc=com does not have a value for the attribute mail 2018-09-25 01:12:07,982,usydind10018,nmsapi,finalize_response,Line=122,PID=25757,INFO,{'path': '/ace/jobs/', 'view': 'ace.views.Job.JobViewSet', 'view_method': 'create', 'remote_addr': '127.0.0.1', 'xff': None, 'host': 'testserver', 'method': 'POST', 'query_params': {}, 'errors': 'Traceback (most recent call last):\n File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 471, in dispatch\n self.initial(request, *args, kwargs)\n File "/opt2/home/pkro/nwsbase/nmsapi/mixins/LoggingMixin.py", line 70, in initial\n super(LoggingMixin, self).initial(request, *args, *kwargs)\n File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 389, in initial\n self.check_permissions(request)\n File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 324, in check_permissions\n request, message=getattr(permission, \'message\', None)\n File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 165, in permission_denied\n raise exceptions.PermissionDenied(detail=message)\nrest_framework.exceptions.PermissionDenied: You do not have permission to perform this action.\n', 'status_code': 403, 'response_ms': 36} 2018-09-25 01:12:07,982,usydind10018,django.request,log_response,Line=228,PID=25757,WARNING,Forbidden: /ace/jobs/ ---------------------------------------------------------------------------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------------------------------------------------------------------------- backend.py 656 WARNING cn=testuser,dc=pc,dc=internal,dc=macquarie,dc=com does not have a value for the attribute sn backend.py 656 WARNING cn=testuser,dc=pc,dc=internal,dc=macquarie,dc=com does not have a value for the attribute mail LoggingMixin.py 122 INFO {'path': '/ace/jobs/', 'view': 'ace.views.Job.JobViewSet', 'view_method': 'create', 'remote_addr': '127.0.0.1', 'xff': None, 'host': 'testserver', 'method': 'POST', 'query_params': {}, 'errors': 'Traceback (most recent call last):\n File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 471, in dispatch\n self.initial(request, args, kwargs)\n File "/opt2/home/pkro/nwsbase/nmsapi/mixins/LoggingMixin.py", line 70, in initial\n super(LoggingMixin, self).initial(request, *args, **kwargs)\n File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 389, in initial\n self.check_permissions(request)\n File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 324, in check_permissions\n request, message=getattr(permission, \'message\', None)\n File "/opt2/python3/lib/python3.6/site-packages/rest_framework/views.py", line 165, in permission_denied\n raise exceptions.PermissionDenied(detail=message)\nrest_framework.exceptions.PermissionDenied: You do not have permission to perform this action.\n', 'status_code': 403, 'response_ms': 36} log.py 228 WARNING Forbidden: /ace/jobs/