Django Testing: DatabaseCreation' object has no attribute '_rollback_works' - django

I have written a example test and I'm trying to run it without creating a new database every time.
The first time I run my test everything is ok (takes sometime due to building the DB):
> REUSE_DB=1 python manage.py test contacts
Ran 1 test in 0.251s
The second time I get the following error:
> REUSE_DB=1 python manage.py test contacts
nosetests --verbosity 1 contacts
AttributeError: 'DatabaseCreation' object has no attribute '_rollback_works'
Why and how do I solve? Thanks.
My Test:
class ExampleTestCase(TestCase):
def test_contact_page(self):
resp = self.client.get('/contact/single/')
self.assertEqual(resp.status_code, 200)
Settings.py
DEBUG = True
TEMPLATE_DEBUG = DEBUG
INSTALLED_APPS += (
'django_nose',
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

Just use nose from github and you're good to go! I belive this is your issue:
https://github.com/jbalogh/django-nose/pull/95
I came across this a long while ago, it is now fixed on the github master, but unfortunately django-nose is not updated on pypi since last year..

Related

Can´t create test database django

I´m trying to test a django application, but when I run python manager.py test I got this error
django.db.utils.ProgrammingError: column deals_dealproposal.billing_branch_launcher_id does not exist
it´s occurs in
File "/migrations/0008_dynamicpackingtype.py", line 18, in run
for proposal in bulk_proposals:
In this point, billing_branch_launcher doesn't really exist, it´s create in migration 27
migrations.AddField(
model_name='dealproposal',
name='billing_branch_launcher',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='billing_branch_launcher', to='clients.CoffeeCompany'),
),
The migration 8 looks like this
class Migration(migrations.Migration):
dependencies = [
('coffeedeals', '0007_auto_20190315_1642'),
('schemas', '0003_dynamicpackingtype')
]
def run(app, schema_editor):
bulk_proposals = md.DealProposal.active.filter(
data__negotiation__packing='bulk',
data__negotiation__packing_type__isnull=False)
for proposal in bulk_proposals:
del proposal.data['negotiation']['packing_type']
proposal.save()
operations = [migrations.RunPython(run, atomic=True)]
How can I fix it?
I suggest install the python library
django-test-without-migrations
Then the migrations file errors don't affect to the tests.
pip install django-test-without-migrations
add it in INSTALLED_APPS (settings.py)
Then run :
python manage.py test --nomigrations
refer:https://pypi.org/project/django-test-without-migrations/

'something here' matching query does not exist

I created a web app and deployed on Heroku successfully even database migrations. When I open the app I see the error like this:
'something here' matching query does not exist.
App URL: https://lp7.herokuapp.com/lp7/
App isn't working and if I remove this data feild from model, then app works but no single data is coming from database. But, when I go to heroku database it shows:
No. of Tables = 28
No. Rows = 220
Size of data = 9.4Mb
It means, the all migrations exists on heroku but not showing on website.
Any solution..?
You need to update the table for model Topbar in Heroku. You can use admin-site to update it.
Also, for future, you might want to change from:
num = TopBar.objects.get()
to
num = TopBar.objects.last()
So it will return the last object created in queryset. It will return None if no object has been created for TopBar
Looking at the traceback https://lp7.herokuapp.com/lp7/ it is bad here
num = TopBar.objects.get() you should pass something matching
if you dont need it do it like
try:
num = TopBar.objects.get(id=1)
except TopBar.DoesNotExist:
pass
#handle if not found logic here
For migrating data from your local database to heroku database is to run:
python manage.py dumpdata yourapp > yourapp/fixtures/app_data.json
Then you need to commit this file to heroku branch, for example:
git commit heroku main
After commiting run the following command to load data into heroku database:
heroku run python manage.py loaddata app_data

python ConfigParser.NoSectionError: - not working on server

Python 2.7
Django 1.10
settings.ini file(located at "/opts/myproject/settings.ini"):
[settings]
DEBUG: True
SECRET_KEY: '5a88V*GuaQgAZa8W2XgvD%dDogQU9Gcc5juq%ax64kyqmzv2rG'
On my django settings file I have:
import os
from ConfigParser import RawConfigParser
config = RawConfigParser()
config.read('/opts/myproject/settings.ini')
SECRET_KEY = config.get('settings', 'SECRET_KEY')
DEBUG = config.get('settings', 'DEBUG')
The setup works fine locally, but when I deploy to my server I get the following error if I try run any django management commands:
ConfigParser.NoSectionError: No section: 'settings'
If I go into Python shell locally I type in the above imports and read the file I get back:
['/opts/myproject/settings.ini']
On server I get back:
[]
I have tried changing "confif.read()" to "config.readfp()" as suggested on here but it didn't work.
Any help or advice is appreciated.

how to ignore missing statemet in jenkins test coverage in django

Is it possible to ignore the missing branch coverage? I am using jenkins for test coverage and pylint testing. Is there any possibility to ingore missing statements and get 100% branch coverage? Maybe a property that can be set in project setting?
I have found the solution of my question.
1) create .coveragerc file in your django project
2) define
JENKINS_TASKS = ('django_jenkins.tasks.run_pylint',)
COVERAGE_EXCLUDES_FOLDERS = ['packsit/migrations/*','packsit/api/v1/images.py']
COVERAGE_RCFILE = '.coveragerc'
in your setting file.
3) .coveragerc file should contains:
[run]
branch = True
omit =
*/.local/*
/usr/*
[report]
exclude_lines =
pragma: no cover
def __repr__
if self\.debug
raise AssertionError
raise NotImplementedError
if 0:
if __name__ == .__main__.:
return
try:
except:
if
self.*
ignore_errors = True
include =
packsit/api/v1/client/*
[html]
directory = coverage_html_report
then run command on terminal:
$ python manage.py jenkins --enable-coverage --coverage-format html --coverage-exclude=COVERAGE_EXCLUDES_FOLDERS
this will exclude 'if, return, self, try , except' from report generated.

Django tests failing on CI after adding django-bower

I have a Django project where I have a few frontend dependencies and so I tried adding django-bower to help me manage them.
I have replaced the previous dependencies with the bower versions and everything seems to be working fine. I'm running my tests with Selenium and when I run them locally, they are passing.
However, when I proceed to test on a CI server, the Selenium tests are failing, with an error message that it is unable to locate an element on the page. This is a form element and I am sure it is there.
I'm trying to figure out why the tests are passing locally but failing on the CI server. Before adding django-bower all tests were passing also in the CI server.
Here is a snippet of the relevant part in the Django settings
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
# Compressor finder
"compressor.finders.CompressorFinder",
# Django bower finder
"djangobower.finders.BowerFinder",
)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
BOWER_COMPONENTS_ROOT = os.path.join(BASE_DIR, 'static', 'js')
BOWER_INSTALLED_APPS = (
'fontawesome#4.3.0',
'jquery-validation#1.13.1',
'magnific-popup#1.0.0',
'masonry#3.2.2',
'materialize#0.95.3',
)
The bower components are installed in static/js/bower_components
The error message provided on the CI server is
NoSuchElementException: Message: {"errorMessage":"Unable to find element with id 'message-form'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"93","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:60555","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"id\", \"sessionId\": \"bb17c920-c5dd-11e4-9c9b-e7fbd91dc2da\", \"value\": \"message-form\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/bb17c920-c5dd-11e4-9c9b-e7fbd91dc2da/element"}}
Any help would really be appreciated. I've Googled everything I can think of and can't seem to find a solution.
This would be still a guess, but I've seen these kind of problems solved by tweaking your tests and adding an Explicit Wait. Instead of just:
form = driver.find_element_by_id('message-form')
use:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
form = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "message-form")))
Basically, you are waiting for the element to become present on a page for 10 seconds, checking every 500 ms. If the element would not become present in 10 seconds, it would throw TimeoutException.
I use Bower with Django projects, but I don't used django-bower. I use it standalone (via bower install), have it store front-end deps in static/bower-components, and refer to that path in templates with the {% static %} template tag. No idea whether doing that would affect your odd test results, but worth a try.