[Solved]: Unit testing migrations [Was: Related model 'company.user' cannot be resolved]

2021-07-07 Thread Mike Dewhirst

On 7/07/2021 9:56 am, Mike Dewhirst wrote:
It seems I have to meddle with history and persuade the testing 
harness that my custom user model has been in the company app from the 
beginning of time. See story below.


Upside is that testing will (might) start working again. Downside is 
I'll go mad.


All upside!

So in summary ...

0. The mission was to move all models (User and UserProfile) from the 
common app to the company app so users and companies would both appear 
in the Admin in the same app. This simplifies the site adminstration 
main menu for new users.


1. In class Meta: in both models User/UserProfile, add db_table = 
common_user/userprofile[1]. This will have no effect and should be 
committed, migrated and deployed to production.


2. Branch the code and switch to create an escape route.

3. Relocate User and UserProfile models from app common to app company[2]

4. Refactor entire codebase using company_ instead of common_ [3]

5. makemigrations[4] but do not migrate to avoid deleting tables.

Now the tricky bit. What I did was probably wrong and any expert is 
welcome to suggest an improvement but because of steps 1 and 2 there was 
always a retreat. The mission here is to tweak the migrations so the 
test harness can create a test database without error.


6. Delete the migration which deletes User and UserProfile tables from 
common


7. Edit company/migrations/0001_initial.py to include the contents of 
the latest migration which created User and UserProfile in company so 
that the test harness thinks they have been there since the beginning. 
Then delete that latest company migration too.


8. Delete all migrations in common/migrations including __pycache__ [5]

9. Cross fingers and run your tests. Resolve any errors by adjusting 
dependencies which includes positioning User and UserProfile higher or 
lower in 0001_initial.py in company/migrations[6].


10. Consider editing your django_migrations table to remove rows 
relating to deleted migrations. This is for future-proofing in case you 
ever decide to put any tables back in the common app. If 0001_initial is 
mentioned in that table it will be a confusing preventer.


11. Merge your successful changes back to your main branch and deploy.


[1] One day I will rename the tables so everything lines up but for now 
that is a step too far


[2] I did try leaving the models in place and importing them into the 
company app but things quickly got messy. Much easier to bite the bullet 
and just physically move the files.


[3] At this point the software should work but unit testing will fail 
because the test database is always generated from the sum total of all 
migrations


[4] This will make table deletions from common and table creations in 
company BUT the creations will be for the current state. This becomes 
significant later in the process.


[5] All migrations in common/migrations were for the only two models in 
the common app. Because the creation migration was for the current 
state, none of the other migrations were needed. However, your mileage 
may vary perhaps if your migrations did other things than just changing 
structure etc. If you also did some data tweaking in some migrations you 
will want to think a bit harder before deleting them.


[6] In my case I needed to put User at the beginning and UserProfile at 
the end of that migration. Here is the relevant piece of my 
company/migrations/0001_initial.py  ... note the db_table in options ...


 


class Migration(migrations.Migration):

initial = True

dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, 
serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, 
verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, 
verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, 
help_text='Designates that this user has all permissions without explicitly 
assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user 
with that username already exists.'}, help_text='Required. 150 characters or 
fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, 
validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], 
verbose_name='username')),
('date_joined', 
models.DateTimeField(default=django.utils.timezone.now, verbose_name='date 
joined')),
('first_name', models.CharField(blank=True, max_length=30, 
verbose_name='short name')),
('last_name', models.CharField(blank=True, max_length=150, 
verbose_name='full name

Unit testing migrations [Was: Related model 'company.user' cannot be resolved]

2021-07-06 Thread Mike Dewhirst
It seems I have to meddle with history and persuade the testing harness 
that my custom user model has been in the company app from the beginning 
of time. See story below.


Upside is that testing will (might) start working again. Downside is 
I'll go mad.


Any ideas?

Thanks

Mike

On 6/07/2021 11:40 am, Mike Dewhirst wrote:
I moved my custom user and userprofile models from my 'common' app 
into my 'company' app by way of locking the model tables first 
(db_table = "common_user" and so on) and just plain refactoring.


That has all worked sort of as expected in that Company and User 
models now appear in the company app space in the Admin which was my 
original motivation.


makemigrations wanted to destroy data with delete/create models in 
order to move them and of course I couldn't let that happen. migrate 
--fake and migrate --fake-initial wouldn't work due to lots of other 
models looking for settings.AUTH_USER_MODEL which Django couldn't find 
in the company app so I finessed my own fake migrations. That also 
seemed to work and the job seemed done.


BUT manage.py test now fails with "Related model 'company.user' cannot 
be resolved"


StackOverflow seems to indicate my finessed migrations are at fault. I 
have tried to tweak the dependencies with no luck as follows ...


# company.migrations.0005_user_userprofile.py
...
    dependencies = [
    ('auth', '0012_alter_user_first_name_max_length'),
    ('company', '0004_auto_20210510_1431'),       # older pre move 
migration

    ('common', '0008_auto_20210705_1740'),        # see below
    ]

    operations = [
    migrations.CreateModel(
    name='User',
    fields=[
    ('id', models.BigAutoField(auto_created=True, 
primary_key=True, serialize=False, verbose_name='ID')),
    ('password', models.CharField(max_length=128, 
verbose_name='password')),

... etc for creating both User and UserProfile models

# common.migrations.0008_auto_20210705_1740.py
...
    dependencies = [
    ('common', '0007_userprofile_job_title'),    # older pre-move 
migration

    ]

    operations = [
    migrations.RemoveField(
    model_name='userprofile',
    name='company',
    ),
    migrations.RemoveField(
    model_name='userprofile',
    name='user',
    ),
    migrations.DeleteModel(
    name='User',
    ),
    migrations.DeleteModel(
    name='UserProfile',
    ),
    ]


Django 3.2.5, Python 3.8

I feel I should have zigged when I should've zagged. Thanks for any 
suggestions


Mike

Traceback (most recent call last):
  File "manage.py", line 21, in 
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\__init__.py", 
line 419, in execute_from_command_line

    utility.execute()
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\__init__.py", 
line 413, in execute

    self.fetch_command(subcommand).run_from_argv(self.argv)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\commands\test.py", 
line 23, in run_from_argv

    super().run_from_argv(argv)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\base.py", 
line 354, in run_from_argv

    self.execute(*args, **cmd_options)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\base.py", 
line 398, in execute

    output = self.handle(*args, **options)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\commands\test.py", 
line 55, in handle

    failures = test_runner.run_tests(test_labels)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\test\runner.py", 
line 725, in run_tests

    old_config = self.setup_databases(aliases=databases)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\test\runner.py", 
line 643, in setup_databases

    return _setup_databases(
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\test\utils.py", line 
179, in setup_databases

    connection.creation.create_test_db(
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\db\backends\base\creation.py", 
line 74, in create_test_db

    call_command(
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\__init__.py", 
line 181, in call_command

    return command.execute(*args, **defaults)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\base.py", 
line 398, in execute

    output = self.handle(*args, **options)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\base.py", 
line 89, in wrapped

    res = handle_func(*args, **kwargs)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\management\commands\migrate.py", 
line 244, in handle

    post_migrate_state = executor.migrate(
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\db\migrations\executor.py", 
line 117, 

Django reverse lookup fails during unit testing

2021-03-16 Thread Derek
Hi

When I open the Django shell (python manage.py shell) and test a reverse
URL:

>>> from django.urls import reverse
>>> reverse('admin:locales_site_changelist')
'/admin/locales/site/'

then it works as expected.

However, when I try and use the same lookup string via a unit test:

from django.test import TestCase
from core.models import CustomUser as User

class TestCaseSimple(TestCase):

def setUp(self):
User.objects.create_superuser(
email='t...@example.com',
password='password')
self.login = self.client.login(
email='t...@example.com',
password='password')
print('Login successful? ', self.login)  # True
url = reverse('admin:locales_site_changelist')


I get this error:

E   django.urls.exceptions.NoReverseMatch: Reverse for
'locales_site_changelist' not found. 'locales_site_changelist' is not a
valid view function or pattern name.


Is there some simple reason why reverse lookup does not work when testing?
(I actually need to use it in a client post request.)

Thanks
Derek

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAF1Wu3NmqC%2BqWK9v%3DNXa%3DOaLc2N3p1dkZ40r1n7gXuCk1gDaQQ%40mail.gmail.com.


Re: Hello ! I'm having some issues in django unit testing. Is there anybody to help ?

2020-11-06 Thread Monaco investment
Am having hard time learning django...can someone please get in touch...I will 
be really grateful... thanks

Get Outlook for Android<https://aka.ms/ghei36>


From: django-users@googlegroups.com  on behalf 
of Nilima Dahal 
Sent: Friday, November 6, 2020 1:11:59 PM
To: Django users 
Subject: Hello ! I'm having some issues in django unit testing. Is there 
anybody to help ?

Hello ! I'm having some issues in django unit testing. Is there anybody to help 
?
I'm having confusion in testing django mixins . Can anyone share his/her git 
with such unit testing or have some experienced shareable codes.

how do I test this ?

def dispatch(self,request,*args,**kwargs):
if self.request.user.is_superuser:
return super().dispatch(request, *args, **kwargs)
return self.handle_no_permission()




--
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to 
django-users+unsubscr...@googlegroups.com<mailto:django-users+unsubscr...@googlegroups.com>.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/44f22b97-7499-4762-92d2-59fa6dd6ad8bn%40googlegroups.com<https://groups.google.com/d/msgid/django-users/44f22b97-7499-4762-92d2-59fa6dd6ad8bn%40googlegroups.com?utm_medium=email_source=footer>.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/AM6PR03MB595708923241D013CF47325AA7EC0%40AM6PR03MB5957.eurprd03.prod.outlook.com.


Hello ! I'm having some issues in django unit testing. Is there anybody to help ?

2020-11-06 Thread Nilima Dahal
Hello ! I'm having some issues in django unit testing. Is there anybody to 
help ? 
I'm having confusion in testing django mixins . Can anyone share his/her 
git with such unit testing or have some experienced shareable codes.

how do I test this ?

def dispatch(self,request,*args,**kwargs):
if self.request.user.is_superuser:
return super().dispatch(request, *args, **kwargs)
return self.handle_no_permission()



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/44f22b97-7499-4762-92d2-59fa6dd6ad8bn%40googlegroups.com.


Re: Unit Testing POST request

2020-02-13 Thread onlinejudge95
On Thu, Feb 13, 2020 at 8:14 PM sachinbg sachin 
wrote:

> Fistly for setup create use instance for setup user credentials then call
> that the reverse url in that post put delite
>

I have already created my test users in the *setUpClass()* method. As
mentioned my problem was not something related to URL dispatching but more
on how to prepare a POST request with the proper payload. I looked into the
documentation and RequestFactory is exactly what i was looking for.


> On Thu, Feb 13, 2020, 8:01 PM Adam Mičuda  wrote:
>
>> Hi,
>> or you can extract the business logic from view to some service and unit
>> test it instead. =)
>>
>> Regards.
>>
>> Adam
>>
>> st 12. 2. 2020 v 21:15 odesílatel onlinejudge95 
>> napsal:
>>
>>> On Wed, Feb 12, 2020 at 6:22 PM onlinejudge95 
>>> wrote:
>>>
 Hi Devs,

 I was implementing unit-tests in my Django project and stumbled upon
 the following issue.

 I want to unit-test my POST route. I do not want to use the test client
 already shipped with Django (using it in my e2e tests). I want to know how
 do I prepare my request object to pass to my view. Here is what I have done
 currently.

 test_views.py

> class CreateBlogTest(BaseViewTest):

 @classmethod
> def setUpClass(cls):
> cls.request.method = "POST"

 def test_create_valid_blog(self):
> self.request.content_type = "application/json"
> self.request._body = json.dumps({"title": "new title", "body":
> "new body"})
>
> response = views.blog_collection(self.request)
> self.assertEqual(response.status_code, 201)
>

 In my view, I am accessing the data through *request.data* and passing
 it to a serializer.

 In my current setting, I am getting a 400 error message when I have
 checked that the user does not exist.

 Any suggestions regarding the same?

 Thanks,
 onlinejudge95

>>>
>>> In case if someone needs it in the future, go and look at
>>> *django.test.RequestFactory *
>>>
>>> https://docs.djangoproject.com/en/3.0/topics/testing/advanced/#django.test.RequestFactory
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/CAD%3DM5eTN3M5iAEvkPoB1fAi%3Du%3DOAXv8kr7S51HmaBsNd8Tubyg%40mail.gmail.com
>>> 
>>> .
>>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/CAB9%3DGXaU4QvmV%3D9fMCcm-NaRUogFtq2Fwd-3MFB5q6QOCxgRhQ%40mail.gmail.com
>> 
>> .
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAOs61rxaSRrE239aZrbBpZSo7QBoZx2BKxx4nBiERhio0RGSJg%40mail.gmail.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAD%3DM5eTyjickDTJVCMgHOGWVpXrTdS%2BRsyiJOtJSBpfWPrb44g%40mail.gmail.com.


Re: Unit Testing POST request

2020-02-13 Thread onlinejudge95
On Thu, Feb 13, 2020 at 8:02 PM Adam Mičuda  wrote:

> Hi,
> or you can extract the business logic from view to some service and unit
> test it instead. =)
>

I am following the same, it's just that I am also performing serialization
as of now in my views, since I want to push it out first, and have
documented the refactor I would be performing. My question was on how to
prepare a post request with proper payload, while i was running this test
my response object was an empty dictionary.

>
> Regards.
>
> Adam
>
> st 12. 2. 2020 v 21:15 odesílatel onlinejudge95 
> napsal:
>
>> On Wed, Feb 12, 2020 at 6:22 PM onlinejudge95 
>> wrote:
>>
>>> Hi Devs,
>>>
>>> I was implementing unit-tests in my Django project and stumbled upon the
>>> following issue.
>>>
>>> I want to unit-test my POST route. I do not want to use the test client
>>> already shipped with Django (using it in my e2e tests). I want to know how
>>> do I prepare my request object to pass to my view. Here is what I have done
>>> currently.
>>>
>>> test_views.py
>>>
 class CreateBlogTest(BaseViewTest):
>>>
>>> @classmethod
 def setUpClass(cls):
 cls.request.method = "POST"
>>>
>>> def test_create_valid_blog(self):
 self.request.content_type = "application/json"
 self.request._body = json.dumps({"title": "new title", "body":
 "new body"})

 response = views.blog_collection(self.request)
 self.assertEqual(response.status_code, 201)

>>>
>>> In my view, I am accessing the data through *request.data* and passing
>>> it to a serializer.
>>>
>>> In my current setting, I am getting a 400 error message when I have
>>> checked that the user does not exist.
>>>
>>> Any suggestions regarding the same?
>>>
>>> Thanks,
>>> onlinejudge95
>>>
>>
>> In case if someone needs it in the future, go and look at
>> *django.test.RequestFactory *
>>
>> https://docs.djangoproject.com/en/3.0/topics/testing/advanced/#django.test.RequestFactory
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/CAD%3DM5eTN3M5iAEvkPoB1fAi%3Du%3DOAXv8kr7S51HmaBsNd8Tubyg%40mail.gmail.com
>> 
>> .
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAB9%3DGXaU4QvmV%3D9fMCcm-NaRUogFtq2Fwd-3MFB5q6QOCxgRhQ%40mail.gmail.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAD%3DM5eTWpMRcZ%2BG_zRf%2B9hB2Xds3SKB%3Dm6PT5C60cCDvGUa5EA%40mail.gmail.com.


Re: Unit Testing POST request

2020-02-13 Thread sachinbg sachin
Fistly for setup create use instance for setup user credentials then call
that the reverse url in that post put delite

On Thu, Feb 13, 2020, 8:01 PM Adam Mičuda  wrote:

> Hi,
> or you can extract the business logic from view to some service and unit
> test it instead. =)
>
> Regards.
>
> Adam
>
> st 12. 2. 2020 v 21:15 odesílatel onlinejudge95 
> napsal:
>
>> On Wed, Feb 12, 2020 at 6:22 PM onlinejudge95 
>> wrote:
>>
>>> Hi Devs,
>>>
>>> I was implementing unit-tests in my Django project and stumbled upon the
>>> following issue.
>>>
>>> I want to unit-test my POST route. I do not want to use the test client
>>> already shipped with Django (using it in my e2e tests). I want to know how
>>> do I prepare my request object to pass to my view. Here is what I have done
>>> currently.
>>>
>>> test_views.py
>>>
 class CreateBlogTest(BaseViewTest):
>>>
>>> @classmethod
 def setUpClass(cls):
 cls.request.method = "POST"
>>>
>>> def test_create_valid_blog(self):
 self.request.content_type = "application/json"
 self.request._body = json.dumps({"title": "new title", "body":
 "new body"})

 response = views.blog_collection(self.request)
 self.assertEqual(response.status_code, 201)

>>>
>>> In my view, I am accessing the data through *request.data* and passing
>>> it to a serializer.
>>>
>>> In my current setting, I am getting a 400 error message when I have
>>> checked that the user does not exist.
>>>
>>> Any suggestions regarding the same?
>>>
>>> Thanks,
>>> onlinejudge95
>>>
>>
>> In case if someone needs it in the future, go and look at
>> *django.test.RequestFactory *
>>
>> https://docs.djangoproject.com/en/3.0/topics/testing/advanced/#django.test.RequestFactory
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/CAD%3DM5eTN3M5iAEvkPoB1fAi%3Du%3DOAXv8kr7S51HmaBsNd8Tubyg%40mail.gmail.com
>> 
>> .
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAB9%3DGXaU4QvmV%3D9fMCcm-NaRUogFtq2Fwd-3MFB5q6QOCxgRhQ%40mail.gmail.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAOs61rxaSRrE239aZrbBpZSo7QBoZx2BKxx4nBiERhio0RGSJg%40mail.gmail.com.


Re: Unit Testing POST request

2020-02-13 Thread Adam Mičuda
Hi,
or you can extract the business logic from view to some service and unit
test it instead. =)

Regards.

Adam

st 12. 2. 2020 v 21:15 odesílatel onlinejudge95 
napsal:

> On Wed, Feb 12, 2020 at 6:22 PM onlinejudge95 
> wrote:
>
>> Hi Devs,
>>
>> I was implementing unit-tests in my Django project and stumbled upon the
>> following issue.
>>
>> I want to unit-test my POST route. I do not want to use the test client
>> already shipped with Django (using it in my e2e tests). I want to know how
>> do I prepare my request object to pass to my view. Here is what I have done
>> currently.
>>
>> test_views.py
>>
>>> class CreateBlogTest(BaseViewTest):
>>
>> @classmethod
>>> def setUpClass(cls):
>>> cls.request.method = "POST"
>>
>> def test_create_valid_blog(self):
>>> self.request.content_type = "application/json"
>>> self.request._body = json.dumps({"title": "new title", "body":
>>> "new body"})
>>>
>>> response = views.blog_collection(self.request)
>>> self.assertEqual(response.status_code, 201)
>>>
>>
>> In my view, I am accessing the data through *request.data* and passing
>> it to a serializer.
>>
>> In my current setting, I am getting a 400 error message when I have
>> checked that the user does not exist.
>>
>> Any suggestions regarding the same?
>>
>> Thanks,
>> onlinejudge95
>>
>
> In case if someone needs it in the future, go and look at
> *django.test.RequestFactory *
>
> https://docs.djangoproject.com/en/3.0/topics/testing/advanced/#django.test.RequestFactory
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAD%3DM5eTN3M5iAEvkPoB1fAi%3Du%3DOAXv8kr7S51HmaBsNd8Tubyg%40mail.gmail.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAB9%3DGXaU4QvmV%3D9fMCcm-NaRUogFtq2Fwd-3MFB5q6QOCxgRhQ%40mail.gmail.com.


Re: Unit Testing POST request

2020-02-12 Thread onlinejudge95
On Wed, Feb 12, 2020 at 6:22 PM onlinejudge95 
wrote:

> Hi Devs,
>
> I was implementing unit-tests in my Django project and stumbled upon the
> following issue.
>
> I want to unit-test my POST route. I do not want to use the test client
> already shipped with Django (using it in my e2e tests). I want to know how
> do I prepare my request object to pass to my view. Here is what I have done
> currently.
>
> test_views.py
>
>> class CreateBlogTest(BaseViewTest):
>
> @classmethod
>> def setUpClass(cls):
>> cls.request.method = "POST"
>
> def test_create_valid_blog(self):
>> self.request.content_type = "application/json"
>> self.request._body = json.dumps({"title": "new title", "body":
>> "new body"})
>>
>> response = views.blog_collection(self.request)
>> self.assertEqual(response.status_code, 201)
>>
>
> In my view, I am accessing the data through *request.data* and passing it
> to a serializer.
>
> In my current setting, I am getting a 400 error message when I have
> checked that the user does not exist.
>
> Any suggestions regarding the same?
>
> Thanks,
> onlinejudge95
>

In case if someone needs it in the future, go and look at
*django.test.RequestFactory *
https://docs.djangoproject.com/en/3.0/topics/testing/advanced/#django.test.RequestFactory

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAD%3DM5eTN3M5iAEvkPoB1fAi%3Du%3DOAXv8kr7S51HmaBsNd8Tubyg%40mail.gmail.com.


Re: Unit Testing POST request

2020-02-12 Thread onlinejudge95
Hi Guys,

Any leads would be appreciated


On Wed, Feb 12, 2020 at 6:22 PM onlinejudge95 
wrote:

> Hi Devs,
>
> I was implementing unit-tests in my Django project and stumbled upon the
> following issue.
>
> I want to unit-test my POST route. I do not want to use the test client
> already shipped with Django (using it in my e2e tests). I want to know how
> do I prepare my request object to pass to my view. Here is what I have done
> currently.
>
> test_views.py
>
>> class CreateBlogTest(BaseViewTest):
>
> @classmethod
>> def setUpClass(cls):
>> cls.request.method = "POST"
>
> def test_create_valid_blog(self):
>> self.request.content_type = "application/json"
>> self.request._body = json.dumps({"title": "new title", "body":
>> "new body"})
>>
>> response = views.blog_collection(self.request)
>> self.assertEqual(response.status_code, 201)
>>
>
> In my view, I am accessing the data through *request.data* and passing it
> to a serializer.
>
> In my current setting, I am getting a 400 error message when I have
> checked that the user does not exist.
>
> Any suggestions regarding the same?
>
> Thanks,
> onlinejudge95
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAD%3DM5eS3nFRxHm_aSqSt8YxFhaZGahF%3DP6Uj0Zco7wafM1%2BHOQ%40mail.gmail.com.


Unit Testing POST request

2020-02-12 Thread onlinejudge95
Hi Devs,

I was implementing unit-tests in my Django project and stumbled upon the
following issue.

I want to unit-test my POST route. I do not want to use the test client
already shipped with Django (using it in my e2e tests). I want to know how
do I prepare my request object to pass to my view. Here is what I have done
currently.

test_views.py

> class CreateBlogTest(BaseViewTest):

@classmethod
> def setUpClass(cls):
> cls.request.method = "POST"

def test_create_valid_blog(self):
> self.request.content_type = "application/json"
> self.request._body = json.dumps({"title": "new title", "body":
> "new body"})
>
> response = views.blog_collection(self.request)
> self.assertEqual(response.status_code, 201)
>

In my view, I am accessing the data through *request.data* and passing it
to a serializer.

In my current setting, I am getting a 400 error message when I have checked
that the user does not exist.

Any suggestions regarding the same?

Thanks,
onlinejudge95

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAD%3DM5eSYo5vSZc8SNGnCET-A10%2B%2Bz6q9j0vqy85TU6r0tE957A%40mail.gmail.com.


Re: Unit-Testing Django Views

2019-03-30 Thread Jorge Gimeno
The online version of the book is pinned to Django 1.11. You may want to
check that out.

-Jorge

On Sat, Mar 30, 2019 at 4:40 AM Test Bot  wrote:

> Sorry for the bother but I finally solved it by using Django's Test Client
> and checking for status_code and template used to render the response in my
> unit-test.
>
> Regards,
> Test Bot
>
> On Sat, Mar 30, 2019 at 5:00 PM Test Bot  wrote:
>
>> I tried removing the {% csrf_token %} from my index.html But it seemed to
>> have no effect. I got the following traceback for further clarity
>>
>> *
>>   START OF TRACEBACK*
>>
>> ===
>> python superlists/manage.py test
>> Creating test database for alias 'default'...
>> System check identified no issues (0 silenced).
>> .F.
>> Destroying test database for alias 'default'...
>> ==
>> FAIL: test_index_view_returns_correct_html (lists.tests.HomePageTest)
>> --
>> Traceback (most recent call last):
>>   File "superlists/lists/tests.py", line 25, in
>> test_index_view_returns_correct_html
>> self.assertEqual(expected_html, actual_html)
>> AssertionError: '> chars]lue="UUl2QtIopzqg9Co4uPlTlSuEPP2O44aMhda056gd4[201 chars]l>\n' !=
>> '> chars]l>\n'
>>
>> --
>> Ran 3 tests in 0.005s
>>
>> FAILED (failures=1)
>>
>> Process finished with exit code 1
>>
>> ===
>> *
>>END OF TRACEBACK*
>>
>>
>> On Fri, Mar 29, 2019 at 12:58 AM Aldian Fazrihady 
>> wrote:
>>
>>> There are several things you can try:
>>> 1. Mocking csrf token functions
>>> 2. Passing the csrf token context from first HTML generation to the
>>> second HTML generation
>>> 3. Wiping out the csrf token parts from both HTML before comparing them.
>>>
>>> On Thu, 28 Mar 2019, 23:54 Simon Charette,  wrote:
>>>
 This is effectively failing because of a mechanism added in 1.10 to
 protect
 against BREACH attacks[0] by salting the CSRF token.

 I'm not aware of any way to disable this mechanism but testing against
 the
 exact HTML returned from a view seems fragile.

 I suggest you use assertContains[1] (with or without html=True) and
 assertTemplateUsed[2] instead.

 Cheers,
 Simon

 [0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
 [1]
 https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
 [2]
 https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed

 Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :
>
> Hi people,
>
> I am following the book Test-Driven Development with Python
> 
>  by
> *Harry J.W. Perceval.* The book is using Django version 1.7 which is
> outdated as of now so I started with version 2.1.
>
> I am trying to unit test my index view. One unit-test that I have
> written is testing whether the index view returns correct HTML or not by
> comparing the input received through
> django.template.loader.render_to_string
> the unit-test fail with the following traceback
> python manage.py test
> Creating test database for alias 'default'...
> .System check identified no issues (0 silenced).
> F.
> ==
> FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
> --
> Traceback (most recent call last):
>   File "tests.py", line 24, in test_index_view_returns_correct_html
> self.assertEqual(expected_html, actual_html)
> AssertionError: ' chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' !=
> ' chars]l>\n'
>
> --
> Ran 3 tests in 0.006s
>
> FAILED (failures=1)
> Destroying test database for alias 'default'...
>
> Process finished with exit code 1
>
>
> It was clear that the csrf token is causing the test to fail. Is there
> any way to test it, or should it be tested? I ask this as when I changed 
> my
> Django version to 1.7, the tests were passing, even after giving the csrf
> token field in the form. I tried going through the changelogs but 1.7 is
> far behind (beginner here). Please find the code snippets, directory
> 

Re: Unit-Testing Django Views

2019-03-30 Thread Test Bot
Sorry for the bother but I finally solved it by using Django's Test Client
and checking for status_code and template used to render the response in my
unit-test.

Regards,
Test Bot

On Sat, Mar 30, 2019 at 5:00 PM Test Bot  wrote:

> I tried removing the {% csrf_token %} from my index.html But it seemed to
> have no effect. I got the following traceback for further clarity
>
> *
> START OF TRACEBACK*
>
> ===
> python superlists/manage.py test
> Creating test database for alias 'default'...
> System check identified no issues (0 silenced).
> .F.
> Destroying test database for alias 'default'...
> ==
> FAIL: test_index_view_returns_correct_html (lists.tests.HomePageTest)
> --
> Traceback (most recent call last):
>   File "superlists/lists/tests.py", line 25, in
> test_index_view_returns_correct_html
> self.assertEqual(expected_html, actual_html)
> AssertionError: ' chars]lue="UUl2QtIopzqg9Co4uPlTlSuEPP2O44aMhda056gd4[201 chars]l>\n' !=
> ' chars]l>\n'
>
> --
> Ran 3 tests in 0.005s
>
> FAILED (failures=1)
>
> Process finished with exit code 1
>
> ===
> *
>  END OF TRACEBACK*
>
>
> On Fri, Mar 29, 2019 at 12:58 AM Aldian Fazrihady 
> wrote:
>
>> There are several things you can try:
>> 1. Mocking csrf token functions
>> 2. Passing the csrf token context from first HTML generation to the
>> second HTML generation
>> 3. Wiping out the csrf token parts from both HTML before comparing them.
>>
>> On Thu, 28 Mar 2019, 23:54 Simon Charette,  wrote:
>>
>>> This is effectively failing because of a mechanism added in 1.10 to
>>> protect
>>> against BREACH attacks[0] by salting the CSRF token.
>>>
>>> I'm not aware of any way to disable this mechanism but testing against
>>> the
>>> exact HTML returned from a view seems fragile.
>>>
>>> I suggest you use assertContains[1] (with or without html=True) and
>>> assertTemplateUsed[2] instead.
>>>
>>> Cheers,
>>> Simon
>>>
>>> [0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
>>> [1]
>>> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
>>> [2]
>>> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed
>>>
>>> Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :

 Hi people,

 I am following the book Test-Driven Development with Python
 
  by
 *Harry J.W. Perceval.* The book is using Django version 1.7 which is
 outdated as of now so I started with version 2.1.

 I am trying to unit test my index view. One unit-test that I have
 written is testing whether the index view returns correct HTML or not by
 comparing the input received through
 django.template.loader.render_to_string
 the unit-test fail with the following traceback
 python manage.py test
 Creating test database for alias 'default'...
 .System check identified no issues (0 silenced).
 F.
 ==
 FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
 --
 Traceback (most recent call last):
   File "tests.py", line 24, in test_index_view_returns_correct_html
 self.assertEqual(expected_html, actual_html)
 AssertionError: '>>> chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' !=
 '>>> chars]l>\n'

 --
 Ran 3 tests in 0.006s

 FAILED (failures=1)
 Destroying test database for alias 'default'...

 Process finished with exit code 1


 It was clear that the csrf token is causing the test to fail. Is there
 any way to test it, or should it be tested? I ask this as when I changed my
 Django version to 1.7, the tests were passing, even after giving the csrf
 token field in the form. I tried going through the changelogs but 1.7 is
 far behind (beginner here). Please find the code snippets, directory
 structure provided below.


 *lists/views.py*










 *from django.http import HttpResponsefrom django.shortcuts import render# 
 Create your views here.def index(request):if request.method == 'POST': 
return 

Re: Unit-Testing Django Views

2019-03-30 Thread Test Bot
I tried removing the {% csrf_token %} from my index.html But it seemed to
have no effect. I got the following traceback for further clarity

*
START OF TRACEBACK*
===
python superlists/manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.F.
Destroying test database for alias 'default'...
==
FAIL: test_index_view_returns_correct_html (lists.tests.HomePageTest)
--
Traceback (most recent call last):
  File "superlists/lists/tests.py", line 25, in
test_index_view_returns_correct_html
self.assertEqual(expected_html, actual_html)
AssertionError: '\n' !=
'\n'

--
Ran 3 tests in 0.005s

FAILED (failures=1)

Process finished with exit code 1
===
*
 END OF TRACEBACK*


On Fri, Mar 29, 2019 at 12:58 AM Aldian Fazrihady  wrote:

> There are several things you can try:
> 1. Mocking csrf token functions
> 2. Passing the csrf token context from first HTML generation to the second
> HTML generation
> 3. Wiping out the csrf token parts from both HTML before comparing them.
>
> On Thu, 28 Mar 2019, 23:54 Simon Charette,  wrote:
>
>> This is effectively failing because of a mechanism added in 1.10 to
>> protect
>> against BREACH attacks[0] by salting the CSRF token.
>>
>> I'm not aware of any way to disable this mechanism but testing against the
>> exact HTML returned from a view seems fragile.
>>
>> I suggest you use assertContains[1] (with or without html=True) and
>> assertTemplateUsed[2] instead.
>>
>> Cheers,
>> Simon
>>
>> [0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
>> [1]
>> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
>> [2]
>> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed
>>
>> Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :
>>>
>>> Hi people,
>>>
>>> I am following the book Test-Driven Development with Python
>>> 
>>>  by
>>> *Harry J.W. Perceval.* The book is using Django version 1.7 which is
>>> outdated as of now so I started with version 2.1.
>>>
>>> I am trying to unit test my index view. One unit-test that I have
>>> written is testing whether the index view returns correct HTML or not by
>>> comparing the input received through
>>> django.template.loader.render_to_string
>>> the unit-test fail with the following traceback
>>> python manage.py test
>>> Creating test database for alias 'default'...
>>> .System check identified no issues (0 silenced).
>>> F.
>>> ==
>>> FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
>>> --
>>> Traceback (most recent call last):
>>>   File "tests.py", line 24, in test_index_view_returns_correct_html
>>> self.assertEqual(expected_html, actual_html)
>>> AssertionError: '>> chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' !=
>>> '>> chars]l>\n'
>>>
>>> --
>>> Ran 3 tests in 0.006s
>>>
>>> FAILED (failures=1)
>>> Destroying test database for alias 'default'...
>>>
>>> Process finished with exit code 1
>>>
>>>
>>> It was clear that the csrf token is causing the test to fail. Is there
>>> any way to test it, or should it be tested? I ask this as when I changed my
>>> Django version to 1.7, the tests were passing, even after giving the csrf
>>> token field in the form. I tried going through the changelogs but 1.7 is
>>> far behind (beginner here). Please find the code snippets, directory
>>> structure provided below.
>>>
>>>
>>> *lists/views.py*
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> *from django.http import HttpResponsefrom django.shortcuts import render# 
>>> Create your views here.def index(request):if request.method == 'POST':  
>>>   return HttpResponse(request.POST['item_text'])return 
>>> render(request, 'index.html')*
>>>
>>>
>>> *lists/test.py*
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> *from django.http import HttpRequestfrom django.template.loader import
>>> render_to_stringfrom django.test import TestCasefrom django.urls import
>>> resolvefrom lists.views import index# Create your tests here.class
>>> IndexViewTest(TestCase): 

Re: Unit-Testing Django Views

2019-03-30 Thread Test Bot
Thanks everyone for the clearance of the problem. I will remove the unit
test's logic to check fir template, it seems a viable test case along with
the status code value.

On Fri, Mar 29, 2019, 2:24 AM Chetan Ganji  wrote:

> There is one more way you could do it
>
>
> class TestIndexPageLoad(TestCase):
>
> def setUp(self):
> self.client = Client()
> self.response = self.client.get('/')
>
> def test_check_response(self):
> self.assertTemplateUsed(self.response, 'index.html')
>
>
>
> Regards,
> Chetan Ganji
> +91-900-483-4183
> ganji.che...@gmail.com
> http://ryucoder.in
>
>
> On Fri, Mar 29, 2019 at 1:56 AM Chetan Ganji 
> wrote:
>
>> I would prefer to just check the status code of the response object.
>> This is what I have done. You have to check if it works for forms with
>> csrf_token or not.
>>
>>
>> class TestReverseUrls(TestCase):
>>
>> def setUp(self):
>> self.client = Client()
>> self.reverseUrls = ['index', 'login', 'register']
>> self.response = {url:self.client.get(reverse(url)) for url in self
>> .reverseUrls}
>>
>> def test_reverse_urls(self):
>> for url in self.reverseUrls:
>> self.assertEqual(self.response[url].status_code, 200)
>>
>>
>>
>> Regards,
>> Chetan Ganji
>> +91-900-483-4183
>> ganji.che...@gmail.com
>> http://ryucoder.in
>>
>>
>> On Fri, Mar 29, 2019 at 12:57 AM Aldian Fazrihady 
>> wrote:
>>
>>> There are several things you can try:
>>> 1. Mocking csrf token functions
>>> 2. Passing the csrf token context from first HTML generation to the
>>> second HTML generation
>>> 3. Wiping out the csrf token parts from both HTML before comparing them.
>>>
>>> On Thu, 28 Mar 2019, 23:54 Simon Charette,  wrote:
>>>
 This is effectively failing because of a mechanism added in 1.10 to
 protect
 against BREACH attacks[0] by salting the CSRF token.

 I'm not aware of any way to disable this mechanism but testing against
 the
 exact HTML returned from a view seems fragile.

 I suggest you use assertContains[1] (with or without html=True) and
 assertTemplateUsed[2] instead.

 Cheers,
 Simon

 [0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
 [1]
 https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
 [2]
 https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed

 Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :
>
> Hi people,
>
> I am following the book Test-Driven Development with Python
> 
>  by
> *Harry J.W. Perceval.* The book is using Django version 1.7 which is
> outdated as of now so I started with version 2.1.
>
> I am trying to unit test my index view. One unit-test that I have
> written is testing whether the index view returns correct HTML or not by
> comparing the input received through
> django.template.loader.render_to_string
> the unit-test fail with the following traceback
> python manage.py test
> Creating test database for alias 'default'...
> .System check identified no issues (0 silenced).
> F.
> ==
> FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
> --
> Traceback (most recent call last):
>   File "tests.py", line 24, in test_index_view_returns_correct_html
> self.assertEqual(expected_html, actual_html)
> AssertionError: ' chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' !=
> ' chars]l>\n'
>
> --
> Ran 3 tests in 0.006s
>
> FAILED (failures=1)
> Destroying test database for alias 'default'...
>
> Process finished with exit code 1
>
>
> It was clear that the csrf token is causing the test to fail. Is there
> any way to test it, or should it be tested? I ask this as when I changed 
> my
> Django version to 1.7, the tests were passing, even after giving the csrf
> token field in the form. I tried going through the changelogs but 1.7 is
> far behind (beginner here). Please find the code snippets, directory
> structure provided below.
>
>
> *lists/views.py*
>
>
>
>
>
>
>
>
>
>
> *from django.http import HttpResponsefrom django.shortcuts import render# 
> Create your views here.def index(request):if request.method == 
> 'POST':return HttpResponse(request.POST['item_text'])return 
> render(request, 'index.html')*
>
>
> *lists/test.py*
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

Re: Unit-Testing Django Views

2019-03-28 Thread Chetan Ganji
There is one more way you could do it


class TestIndexPageLoad(TestCase):

def setUp(self):
self.client = Client()
self.response = self.client.get('/')

def test_check_response(self):
self.assertTemplateUsed(self.response, 'index.html')



Regards,
Chetan Ganji
+91-900-483-4183
ganji.che...@gmail.com
http://ryucoder.in


On Fri, Mar 29, 2019 at 1:56 AM Chetan Ganji  wrote:

> I would prefer to just check the status code of the response object.
> This is what I have done. You have to check if it works for forms with
> csrf_token or not.
>
>
> class TestReverseUrls(TestCase):
>
> def setUp(self):
> self.client = Client()
> self.reverseUrls = ['index', 'login', 'register']
> self.response = {url:self.client.get(reverse(url)) for url in self
> .reverseUrls}
>
> def test_reverse_urls(self):
> for url in self.reverseUrls:
> self.assertEqual(self.response[url].status_code, 200)
>
>
>
> Regards,
> Chetan Ganji
> +91-900-483-4183
> ganji.che...@gmail.com
> http://ryucoder.in
>
>
> On Fri, Mar 29, 2019 at 12:57 AM Aldian Fazrihady 
> wrote:
>
>> There are several things you can try:
>> 1. Mocking csrf token functions
>> 2. Passing the csrf token context from first HTML generation to the
>> second HTML generation
>> 3. Wiping out the csrf token parts from both HTML before comparing them.
>>
>> On Thu, 28 Mar 2019, 23:54 Simon Charette,  wrote:
>>
>>> This is effectively failing because of a mechanism added in 1.10 to
>>> protect
>>> against BREACH attacks[0] by salting the CSRF token.
>>>
>>> I'm not aware of any way to disable this mechanism but testing against
>>> the
>>> exact HTML returned from a view seems fragile.
>>>
>>> I suggest you use assertContains[1] (with or without html=True) and
>>> assertTemplateUsed[2] instead.
>>>
>>> Cheers,
>>> Simon
>>>
>>> [0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
>>> [1]
>>> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
>>> [2]
>>> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed
>>>
>>> Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :

 Hi people,

 I am following the book Test-Driven Development with Python
 
  by
 *Harry J.W. Perceval.* The book is using Django version 1.7 which is
 outdated as of now so I started with version 2.1.

 I am trying to unit test my index view. One unit-test that I have
 written is testing whether the index view returns correct HTML or not by
 comparing the input received through
 django.template.loader.render_to_string
 the unit-test fail with the following traceback
 python manage.py test
 Creating test database for alias 'default'...
 .System check identified no issues (0 silenced).
 F.
 ==
 FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
 --
 Traceback (most recent call last):
   File "tests.py", line 24, in test_index_view_returns_correct_html
 self.assertEqual(expected_html, actual_html)
 AssertionError: '>>> chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' !=
 '>>> chars]l>\n'

 --
 Ran 3 tests in 0.006s

 FAILED (failures=1)
 Destroying test database for alias 'default'...

 Process finished with exit code 1


 It was clear that the csrf token is causing the test to fail. Is there
 any way to test it, or should it be tested? I ask this as when I changed my
 Django version to 1.7, the tests were passing, even after giving the csrf
 token field in the form. I tried going through the changelogs but 1.7 is
 far behind (beginner here). Please find the code snippets, directory
 structure provided below.


 *lists/views.py*










 *from django.http import HttpResponsefrom django.shortcuts import render# 
 Create your views here.def index(request):if request.method == 'POST': 
return HttpResponse(request.POST['item_text'])return 
 render(request, 'index.html')*


 *lists/test.py*


























 *from django.http import HttpRequestfrom django.template.loader import
 render_to_stringfrom django.test import TestCasefrom django.urls import
 resolvefrom lists.views import index# Create your tests here.class
 IndexViewTest(TestCase):def
 test_root_url_resolves_to_home_page_view(self):   [...]def
 test_index_view_returns_correct_html(self):request = 

Re: Unit-Testing Django Views

2019-03-28 Thread Chetan Ganji
I would prefer to just check the status code of the response object.
This is what I have done. You have to check if it works for forms with
csrf_token or not.


class TestReverseUrls(TestCase):

def setUp(self):
self.client = Client()
self.reverseUrls = ['index', 'login', 'register']
self.response = {url:self.client.get(reverse(url)) for url in self
.reverseUrls}

def test_reverse_urls(self):
for url in self.reverseUrls:
self.assertEqual(self.response[url].status_code, 200)



Regards,
Chetan Ganji
+91-900-483-4183
ganji.che...@gmail.com
http://ryucoder.in


On Fri, Mar 29, 2019 at 12:57 AM Aldian Fazrihady  wrote:

> There are several things you can try:
> 1. Mocking csrf token functions
> 2. Passing the csrf token context from first HTML generation to the second
> HTML generation
> 3. Wiping out the csrf token parts from both HTML before comparing them.
>
> On Thu, 28 Mar 2019, 23:54 Simon Charette,  wrote:
>
>> This is effectively failing because of a mechanism added in 1.10 to
>> protect
>> against BREACH attacks[0] by salting the CSRF token.
>>
>> I'm not aware of any way to disable this mechanism but testing against the
>> exact HTML returned from a view seems fragile.
>>
>> I suggest you use assertContains[1] (with or without html=True) and
>> assertTemplateUsed[2] instead.
>>
>> Cheers,
>> Simon
>>
>> [0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
>> [1]
>> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
>> [2]
>> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed
>>
>> Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :
>>>
>>> Hi people,
>>>
>>> I am following the book Test-Driven Development with Python
>>> 
>>>  by
>>> *Harry J.W. Perceval.* The book is using Django version 1.7 which is
>>> outdated as of now so I started with version 2.1.
>>>
>>> I am trying to unit test my index view. One unit-test that I have
>>> written is testing whether the index view returns correct HTML or not by
>>> comparing the input received through
>>> django.template.loader.render_to_string
>>> the unit-test fail with the following traceback
>>> python manage.py test
>>> Creating test database for alias 'default'...
>>> .System check identified no issues (0 silenced).
>>> F.
>>> ==
>>> FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
>>> --
>>> Traceback (most recent call last):
>>>   File "tests.py", line 24, in test_index_view_returns_correct_html
>>> self.assertEqual(expected_html, actual_html)
>>> AssertionError: '>> chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' !=
>>> '>> chars]l>\n'
>>>
>>> --
>>> Ran 3 tests in 0.006s
>>>
>>> FAILED (failures=1)
>>> Destroying test database for alias 'default'...
>>>
>>> Process finished with exit code 1
>>>
>>>
>>> It was clear that the csrf token is causing the test to fail. Is there
>>> any way to test it, or should it be tested? I ask this as when I changed my
>>> Django version to 1.7, the tests were passing, even after giving the csrf
>>> token field in the form. I tried going through the changelogs but 1.7 is
>>> far behind (beginner here). Please find the code snippets, directory
>>> structure provided below.
>>>
>>>
>>> *lists/views.py*
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> *from django.http import HttpResponsefrom django.shortcuts import render# 
>>> Create your views here.def index(request):if request.method == 'POST':  
>>>   return HttpResponse(request.POST['item_text'])return 
>>> render(request, 'index.html')*
>>>
>>>
>>> *lists/test.py*
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> *from django.http import HttpRequestfrom django.template.loader import
>>> render_to_stringfrom django.test import TestCasefrom django.urls import
>>> resolvefrom lists.views import index# Create your tests here.class
>>> IndexViewTest(TestCase):def
>>> test_root_url_resolves_to_home_page_view(self):   [...]def
>>> test_index_view_returns_correct_html(self):request = HttpRequest()
>>>   response = index(request)actual_html =
>>> response.content.decode()expected_html =
>>> render_to_string('index.html', request=request)
>>> self.assertEqual(expected_html, actual_html)def
>>> test_index_view_can_save_a_post_request(self):   [...]requirements.txt*
>>>
>>>
>>>
>>>
>>>
>>> *Django==2.1.7pytz==2018.9selenium==3.141.0urllib3==1.24.*
>>> *settings.py*
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> *[...]# Application definitionINSTALLED_APPS = [ 'django.contrib.admin',
>>> 

Re: Unit-Testing Django Views

2019-03-28 Thread Aldian Fazrihady
There are several things you can try:
1. Mocking csrf token functions
2. Passing the csrf token context from first HTML generation to the second
HTML generation
3. Wiping out the csrf token parts from both HTML before comparing them.

On Thu, 28 Mar 2019, 23:54 Simon Charette,  wrote:

> This is effectively failing because of a mechanism added in 1.10 to protect
> against BREACH attacks[0] by salting the CSRF token.
>
> I'm not aware of any way to disable this mechanism but testing against the
> exact HTML returned from a view seems fragile.
>
> I suggest you use assertContains[1] (with or without html=True) and
> assertTemplateUsed[2] instead.
>
> Cheers,
> Simon
>
> [0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
> [1]
> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
> [2]
> https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed
>
> Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :
>>
>> Hi people,
>>
>> I am following the book Test-Driven Development with Python
>> 
>>  by
>> *Harry J.W. Perceval.* The book is using Django version 1.7 which is
>> outdated as of now so I started with version 2.1.
>>
>> I am trying to unit test my index view. One unit-test that I have written
>> is testing whether the index view returns correct HTML or not by comparing
>> the input received through
>> django.template.loader.render_to_string
>> the unit-test fail with the following traceback
>> python manage.py test
>> Creating test database for alias 'default'...
>> .System check identified no issues (0 silenced).
>> F.
>> ==
>> FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
>> --
>> Traceback (most recent call last):
>>   File "tests.py", line 24, in test_index_view_returns_correct_html
>> self.assertEqual(expected_html, actual_html)
>> AssertionError: '> chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' !=
>> '> chars]l>\n'
>>
>> --
>> Ran 3 tests in 0.006s
>>
>> FAILED (failures=1)
>> Destroying test database for alias 'default'...
>>
>> Process finished with exit code 1
>>
>>
>> It was clear that the csrf token is causing the test to fail. Is there
>> any way to test it, or should it be tested? I ask this as when I changed my
>> Django version to 1.7, the tests were passing, even after giving the csrf
>> token field in the form. I tried going through the changelogs but 1.7 is
>> far behind (beginner here). Please find the code snippets, directory
>> structure provided below.
>>
>>
>> *lists/views.py*
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> *from django.http import HttpResponsefrom django.shortcuts import render# 
>> Create your views here.def index(request):if request.method == 'POST':   
>>  return HttpResponse(request.POST['item_text'])return 
>> render(request, 'index.html')*
>>
>>
>> *lists/test.py*
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> *from django.http import HttpRequestfrom django.template.loader import
>> render_to_stringfrom django.test import TestCasefrom django.urls import
>> resolvefrom lists.views import index# Create your tests here.class
>> IndexViewTest(TestCase):def
>> test_root_url_resolves_to_home_page_view(self):   [...]def
>> test_index_view_returns_correct_html(self):request = HttpRequest()
>>   response = index(request)actual_html =
>> response.content.decode()expected_html =
>> render_to_string('index.html', request=request)
>> self.assertEqual(expected_html, actual_html)def
>> test_index_view_can_save_a_post_request(self):   [...]requirements.txt*
>>
>>
>>
>>
>>
>> *Django==2.1.7pytz==2018.9selenium==3.141.0urllib3==1.24.*
>> *settings.py*
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> *[...]# Application definitionINSTALLED_APPS = [ 'django.contrib.admin',
>> 'django.contrib.auth', 'django.contrib.contenttypes',
>> 'django.contrib.sessions', 'django.contrib.messages',
>> 'django.contrib.staticfiles', 'lists',][...]*
>> *Directory Structure*
>>
>> [image: Screen Shot 2019-03-28 at 9.36.56 PM.png]
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/7f0f12be-fc3e-43c3-ba07-e48158def051%40googlegroups.com
> 

Re: Unit-Testing Django Views

2019-03-28 Thread Simon Charette
This is effectively failing because of a mechanism added in 1.10 to protect
against BREACH attacks[0] by salting the CSRF token.

I'm not aware of any way to disable this mechanism but testing against the
exact HTML returned from a view seems fragile.

I suggest you use assertContains[1] (with or without html=True) and
assertTemplateUsed[2] instead.

Cheers,
Simon

[0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
[1] 
https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
[2] 
https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed

Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :
>
> Hi people,
>
> I am following the book Test-Driven Development with Python 
> 
>  by 
> *Harry J.W. Perceval.* The book is using Django version 1.7 which is 
> outdated as of now so I started with version 2.1.
>
> I am trying to unit test my index view. One unit-test that I have written 
> is testing whether the index view returns correct HTML or not by comparing 
> the input received through
> django.template.loader.render_to_string
> the unit-test fail with the following traceback
> python manage.py test
> Creating test database for alias 'default'...
> .System check identified no issues (0 silenced).
> F.
> ==
> FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
> --
> Traceback (most recent call last):
>   File "tests.py", line 24, in test_index_view_returns_correct_html
> self.assertEqual(expected_html, actual_html)
> AssertionError: ' chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' != 
> ' chars]l>\n'
>
> --
> Ran 3 tests in 0.006s
>
> FAILED (failures=1)
> Destroying test database for alias 'default'...
>
> Process finished with exit code 1
>
>
> It was clear that the csrf token is causing the test to fail. Is there any 
> way to test it, or should it be tested? I ask this as when I changed my 
> Django version to 1.7, the tests were passing, even after giving the csrf 
> token field in the form. I tried going through the changelogs but 1.7 is 
> far behind (beginner here). Please find the code snippets, directory 
> structure provided below.
>
>
> *lists/views.py*
>
>
>
>
>
>
>
>
>
>
> *from django.http import HttpResponsefrom django.shortcuts import render# 
> Create your views here.def index(request):if request.method == 'POST':
> return HttpResponse(request.POST['item_text'])return render(request, 
> 'index.html')*
>
>
> *lists/test.py*
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *from django.http import HttpRequestfrom django.template.loader import 
> render_to_stringfrom django.test import TestCasefrom django.urls import 
> resolvefrom lists.views import index# Create your tests here.class 
> IndexViewTest(TestCase):def 
> test_root_url_resolves_to_home_page_view(self):   [...]def 
> test_index_view_returns_correct_html(self):request = HttpRequest()  
>   response = index(request)actual_html = 
> response.content.decode()expected_html = 
> render_to_string('index.html', request=request)
> self.assertEqual(expected_html, actual_html)def 
> test_index_view_can_save_a_post_request(self):   [...]requirements.txt*
>
>
>
>
>
> *Django==2.1.7pytz==2018.9selenium==3.141.0urllib3==1.24.*
> *settings.py*
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *[...]# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 
> 'django.contrib.auth', 'django.contrib.contenttypes', 
> 'django.contrib.sessions', 'django.contrib.messages', 
> 'django.contrib.staticfiles', 'lists',][...]*
> *Directory Structure*
>
> [image: Screen Shot 2019-03-28 at 9.36.56 PM.png]
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/7f0f12be-fc3e-43c3-ba07-e48158def051%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Unit-Testing Django Views

2019-03-28 Thread OnlineJudge95
Hi people,

I am following the book Test-Driven Development with Python 

 by 
*Harry J.W. Perceval.* The book is using Django version 1.7 which is 
outdated as of now so I started with version 2.1.

I am trying to unit test my index view. One unit-test that I have written 
is testing whether the index view returns correct HTML or not by comparing 
the input received through
django.template.loader.render_to_string
the unit-test fail with the following traceback
python manage.py test
Creating test database for alias 'default'...
.System check identified no issues (0 silenced).
F.
==
FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
--
Traceback (most recent call last):
  File "tests.py", line 24, in test_index_view_returns_correct_html
self.assertEqual(expected_html, actual_html)
AssertionError: '\n' != 
'\n'

--
Ran 3 tests in 0.006s

FAILED (failures=1)
Destroying test database for alias 'default'...

Process finished with exit code 1


It was clear that the csrf token is causing the test to fail. Is there any 
way to test it, or should it be tested? I ask this as when I changed my 
Django version to 1.7, the tests were passing, even after giving the csrf 
token field in the form. I tried going through the changelogs but 1.7 is 
far behind (beginner here). Please find the code snippets, directory 
structure provided below.


*lists/views.py*










*from django.http import HttpResponsefrom django.shortcuts import render# 
Create your views here.def index(request):if request.method == 'POST':  
  return HttpResponse(request.POST['item_text'])return render(request, 
'index.html')*


*lists/test.py*


























*from django.http import HttpRequestfrom django.template.loader import 
render_to_stringfrom django.test import TestCasefrom django.urls import 
resolvefrom lists.views import index# Create your tests here.class 
IndexViewTest(TestCase):def 
test_root_url_resolves_to_home_page_view(self):   [...]def 
test_index_view_returns_correct_html(self):request = HttpRequest()  
  response = index(request)actual_html = 
response.content.decode()expected_html = 
render_to_string('index.html', request=request)
self.assertEqual(expected_html, actual_html)def 
test_index_view_can_save_a_post_request(self):   [...]requirements.txt*





*Django==2.1.7pytz==2018.9selenium==3.141.0urllib3==1.24.*
*settings.py*















*[...]# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 
'django.contrib.auth', 'django.contrib.contenttypes', 
'django.contrib.sessions', 'django.contrib.messages', 
'django.contrib.staticfiles', 'lists',][...]*
*Directory Structure*

[image: Screen Shot 2019-03-28 at 9.36.56 PM.png]

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ed387060-93e5-4d0c-a4a6-a5204e6c097f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django unit testing and pk's changing

2018-10-24 Thread David
The issue was my using incorrect def get_absolute_url's in my model  My 
error.

On Wednesday, 24 October 2018 12:24:07 UTC+1, David wrote:
>
> Hi
>
> When I run tests on my app they run through fine.
>
> When I run tests just using "manage.py test" the app mentioned above 
> contains failures.
>
> Example code:
>
> def test_lumpsum_get_absolute_url(self):
> lumpsum = LumpSum.objects.get()
> self.assertEquals(lumpsum.get_absolute_url(),
>   reverse('estates:lumpsum', kwargs={
>   'case_pk': self.case.pk,
>   'client_pk': self.client.pk,
>   })
>   )
>
>
> Traceback (most recent call last):
>   File "path\test_models.py", line 541, in test_lumpsum_get_absolute_url
> 'client_pk': lumpsum.client.pk,
> AssertionError: '/estates/53/lumpsum/98/' != '/estates/113/lumpsum/98/'
> - /estates/53/lumpsum/98/
> ?  ^
> + /estates/113/lumpsum/98/
> ?  
>
> The case.pk (53 and 113 above) changes, yet the client.pk (98) does not.
>
> I understand that setUp is run for each test, so expect the pk to rise, 
> but I cannot fathom why only one of the PKs is changing.
>
> In setUp:
>
> self.case = Case.objects.create(
> name='example case',
> adviser=self.adviser,
> meeting_date='2018-01-01',
> urgency='N',
> assignment_trust='N',
> expression_wishes='N',
> lifetime_planning='N',
> home_savings='Y',
> marriage_death='N',
> inheritance_tax='Y',
> inheritance_creditors='N',
> inheritance_divorce='Y',
> further_iht='N',
> comment='just another comment',
> )
>
> self.client = Client.objects.create(
> case=self.case,
> prefix='Mr',
> first_name='first name',
> last_name='last name',
> date_of_birth='1900-01-01',
> gender='M',
> residence='EN',
> address_1='10 C',
> city='city',
> postcode='SOL',
> telephone='0211 11',
> marital_status='SI',
> have_will='N',
> existing_poa='N',
> dependant='N',
> share_house='N',
> )
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/f72902ab-9dd3-4cfc-8b05-f9dc090d0a8b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django unit testing and pk's changing

2018-10-24 Thread David
Hi

When I run tests on my app they run through fine.

When I run tests just using "manage.py test" the app mentioned above 
contains failures.

Example code:

def test_lumpsum_get_absolute_url(self):
lumpsum = LumpSum.objects.get()
self.assertEquals(lumpsum.get_absolute_url(),
  reverse('estates:lumpsum', kwargs={
  'case_pk': self.case.pk,
  'client_pk': self.client.pk,
  })
  )


Traceback (most recent call last):
  File "path\test_models.py", line 541, in test_lumpsum_get_absolute_url
'client_pk': lumpsum.client.pk,
AssertionError: '/estates/53/lumpsum/98/' != '/estates/113/lumpsum/98/'
- /estates/53/lumpsum/98/
?  ^
+ /estates/113/lumpsum/98/
?  

The case.pk (53 and 113 above) changes, yet the client.pk (98) does not.

I understand that setUp is run for each test, so expect the pk to rise, but 
I cannot fathom why only one of the PKs is changing.

In setUp:

self.case = Case.objects.create(
name='example case',
adviser=self.adviser,
meeting_date='2018-01-01',
urgency='N',
assignment_trust='N',
expression_wishes='N',
lifetime_planning='N',
home_savings='Y',
marriage_death='N',
inheritance_tax='Y',
inheritance_creditors='N',
inheritance_divorce='Y',
further_iht='N',
comment='just another comment',
)

self.client = Client.objects.create(
case=self.case,
prefix='Mr',
first_name='first name',
last_name='last name',
date_of_birth='1900-01-01',
gender='M',
residence='EN',
address_1='10 C',
city='city',
postcode='SOL',
telephone='0211 11',
marital_status='SI',
have_will='N',
existing_poa='N',
dependant='N',
share_house='N',
)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/05ea3e16-0cba-446c-8166-00454ded503e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing models.py

2018-05-14 Thread Melvyn Sopacua
Hi Mark,

On zondag 13 mei 2018 18:11:07 CEST Mark Phillips wrote:
> What should be unit tested in models.py? I assume the storing of data and
> retrieving of data from the database does not need to be tested, as I
> further assume django has a full set of tests for those operations.

You should test your business requirements. Even for those operations. Best 
illustrated:

# models.py
class Customer(models.Model):
email = models.EmailField()
name = models.CharField(max_length=100)

# tests.py

class CustomerTestCase(TestCase):
def test_create(self):
data = { 'email': 'i...@example.com', name='John Doe' }
  first = Customer.objects.create(**data)
with self.assertRaisesMessage(IntegrityError, 'duplicate key 
value'):
second = Customer.objects.create(**data)

This test will fail cause there's no unique constrain on email, which is 
likely to be a business requirement. You should test it. Especially because if 
someone refactor years down the line and accidentally removes the requirement, 
you have a problem.

> * Labels for all fields
> something like
> def test_first_name_label(self):
> author=Author.objects.get(id=1)
> field_label = author._meta.get_field('first_name').verbose_name
> self.assertEquals(field_label,'first name')

I would say this is exactly the thing you wouldn't test: anything dealing with 
_meta. Test these further downstream, by verifying form labels and their 
translated version if it applies. And I'd say the exact wording of a form 
label may not be at all important, so you could skip this.

-- 
Melvyn Sopacua

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2172791.13n9OJESef%40fritzbook.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing models.py

2018-05-14 Thread 'Anthony Flury' via Django users

I would agree with that - test any custom functionality -

 * Custom methods (including __str__ and __repr__)
 * custom managers
 * Triggers (that maybe save custom fields on update)
 * validations - testing to ensure that the right validation is
   performed on that field - i.e. you linked the right field with the
   right validation.

I would do a cursory test that you can save and retrieve an object - 
just to make sure that you have executed your migrations correctly



On 13/05/18 19:08, Jani Tiainen wrote:

Hi,

In general you don't need to test your models if you don't use 
anything special there. If you do have properties or methods on models 
that do something that is good to test that they return correct values 
or do correct things.




On Sun, May 13, 2018 at 7:11 PM, Mark Phillips 
> wrote:


What should be unit tested in models.py? I assume the storing of
data and retrieving of data from the database does not need to be
tested, as I further assume django has a full set of tests for
those operations.

I can see testing these parts of models.py

* All custom methods

* Labels for all fields
something like
def test_first_name_label(self):
        author=Author.objects.get(id=1)
        field_label =
author._meta.get_field('first_name').verbose_name
        self.assertEquals(field_label,'first name')

* Field attributes (eg length of CharField)? Is this really
necessary, as I would again assume django covers this in their
unit tests?

Anything else that I am missing?

Thanks!

Mark
-- 
You received this message because you are subscribed to the Google

Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it,
send an email to django-users+unsubscr...@googlegroups.com
.
To post to this group, send email to django-users@googlegroups.com
.
Visit this group at https://groups.google.com/group/django-users
.
To view this discussion on the web visit

https://groups.google.com/d/msgid/django-users/CAEqej2P0_sZt2j06nf0OnOL%2BE%3DuVa1Cs0BOFmTx8vjQm6-io2Q%40mail.gmail.com

.
For more options, visit https://groups.google.com/d/optout
.




--
Jani Tiainen

- Well planned is half done, and a half done has been sufficient before...
--
You received this message because you are subscribed to the Google 
Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 
an email to django-users+unsubscr...@googlegroups.com 
.
To post to this group, send email to django-users@googlegroups.com 
.

Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHn91oeJYPGbLaJAZbJqd3jxbDcY6m3d8e2fSE06_E_ZwXXosQ%40mail.gmail.com 
.

For more options, visit https://groups.google.com/d/optout.



--
--
Anthony Flury
email : *anthony.fl...@btinternet.com*
Twitter : *@TonyFlury *

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9822baae-9064-2a48-ede3-c4f2c2b4d031%40btinternet.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing models.py

2018-05-13 Thread Jani Tiainen
Hi,

In general you don't need to test your models if you don't use anything
special there. If you do have properties or methods on models that do
something that is good to test that they return correct values or do
correct things.



On Sun, May 13, 2018 at 7:11 PM, Mark Phillips 
wrote:

> What should be unit tested in models.py? I assume the storing of data and
> retrieving of data from the database does not need to be tested, as I
> further assume django has a full set of tests for those operations.
>
> I can see testing these parts of models.py
>
> * All custom methods
>
> * Labels for all fields
> something like
> def test_first_name_label(self):
> author=Author.objects.get(id=1)
> field_label = author._meta.get_field('first_name').verbose_name
> self.assertEquals(field_label,'first name')
>
> * Field attributes (eg length of CharField)? Is this really necessary, as
> I would again assume django covers this in their unit tests?
>
> Anything else that I am missing?
>
> Thanks!
>
> Mark
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/CAEqej2P0_sZt2j06nf0OnOL%2BE%
> 3DuVa1Cs0BOFmTx8vjQm6-io2Q%40mail.gmail.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Jani Tiainen

- Well planned is half done, and a half done has been sufficient before...

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHn91oeJYPGbLaJAZbJqd3jxbDcY6m3d8e2fSE06_E_ZwXXosQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Unit testing models.py

2018-05-13 Thread Mark Phillips
What should be unit tested in models.py? I assume the storing of data and
retrieving of data from the database does not need to be tested, as I
further assume django has a full set of tests for those operations.

I can see testing these parts of models.py

* All custom methods

* Labels for all fields
something like
def test_first_name_label(self):
author=Author.objects.get(id=1)
field_label = author._meta.get_field('first_name').verbose_name
self.assertEquals(field_label,'first name')

* Field attributes (eg length of CharField)? Is this really necessary, as I
would again assume django covers this in their unit tests?

Anything else that I am missing?

Thanks!

Mark

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEqej2P0_sZt2j06nf0OnOL%2BE%3DuVa1Cs0BOFmTx8vjQm6-io2Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing Multiselect fields not loading as expected

2017-05-08 Thread Trevor Woolley
Thanks Tim.

On Mon, May 8, 2017 at 8:49 PM, Tim Graham  wrote:

> This is because you have a module level query at my_choices = [(m['id'],
> m['displayname']) for m in get_my_list()].
>
> There's a documentation warning about this; see the "Finding data from
> your production database when running tests?" note in ​this section [0].
>
> [0] https://docs.djangoproject.com/en/dev/topics/testing/
> overview/#the-test-database
>
>
> On Sunday, May 7, 2017 at 9:05:09 PM UTC-4, Trevor Woolley wrote:
>>
>> Further investigation shows this as failing outside of a test scenario,
>> and the "my_choices" is not being updated, unless the server (be that the
>> ./manage.py runserver" or a production apache server) is restarted.
>>
>> Rgds
>> Trevor
>>
>> On Friday, May 5, 2017 at 3:20:04 PM UTC+10, Trevor Woolley wrote:
>>>
>>> Hi, when I run a unittest on a form containing a MultipleChoiceField,
>>> and in the unittest I test setting what I think should be a valid field, it
>>> does not pass. It appears that field in question extracts the data is uses
>>> for the test before the test database is created, and actually uses the
>>> production database for the values.
>>>
>>> The result of the test and the (altered snippets) are below, if anyone
>>> can help I'd be grateful.
>>>
>>> The below example includes a mock of the data fill function, but there
>>> is no difference in the ultimate response, if the mock setup is not used.
>>> If the production database contains the correct IDs the test passes.
>>>
>>> Rgds
>>> Trevor
>>>
>>> #
>>> # forms.py snippet
>>> #
>>> # appropriate imports
>>>
>>> def get_my_list():
>>> """ Function to get the complete stuff list for multiselect """
>>> result = []
>>> my_stuff = Stuff.objects.all()
>>> for stuff in my_stuff:
>>> displayname = "%s (%s)" % (stuff.name1, stuff.name2)
>>> result.append({"id": str(stuff.id), "displayname": displayname})
>>> print("REAL --> %s" % result)
>>> return sorted(result, key=itemgetter("displayname"))
>>>
>>>
>>> class DispLayIssueForm(forms.Form):
>>> """ Class to manage the changes / adds for the extra Stuff model """
>>> description = forms.CharField(
>>> label='Short Description',
>>> max_length=199,
>>> strip=True
>>> )
>>> my_choices = [(m['id'], m['displayname']) for m in get_my_list()]
>>> print("In Form --> %s" % my_choices)
>>>
>>> stuff = forms.MultipleChoiceField(
>>> widget=forms.SelectMultiple(attrs={'size': '10'}),
>>> choices=my_choices,
>>> label="My Stuff",
>>> required=False,
>>> )
>>> db_id = forms.CharField(widget=forms.HiddenInput)
>>>
>>> def clean(self):
>>> """ Form Clean function """
>>> # 
>>>
>>> def save(self):
>>> """ Form Save function """
>>> # 
>>>
>>> def update(self):
>>> """ Form Update function """
>>> # 
>>>
>>>
>>> #
>>> # test_forms
>>> #
>>> # appropriate imports
>>> # django.test import TestCase
>>>
>>>
>>> def mocked_get_my_list():
>>> """ Mocking the function so that it grabs the test data """
>>> result = []
>>> my_stuff = Stuff.objects.all()
>>> for stuff in my_stuff:
>>> displayname = "%s (%s)" % (stuff.name1, stuff.name2)
>>> result.append({"id": str(stuff.id), "displayname": displayname})
>>> print("MOCKED --> %s" % result)
>>> return result
>>>
>>> class DispLayIssueFormTests(TestCase):
>>> """ Class to test the display issue form """
>>>
>>> def setUp(self):
>>> """ Initial setup just creates two stuff entries """
>>> self.name1 = create_stuff("foo1", "bar1")
>>> self.name2 = create_stuff("foo2", "bar2")
>>>
>>> def tearDown(self):
>>> """ Final tear downs """
>>> self.name1.delete()
>>> self.name2.delete()
>>>
>>> # Other tests that leave the stuff fields empty pass
>>>
>>> @mock.patch('form.get_my_list')
>>> def test_valid_save2(self, mock_list):
>>> """ Test to ensure a valid save succeeds - with stuff """
>>> print("START")
>>> mock_list.side_effect = mocked_get_my_list()
>>> testform = DispLayIssueForm({
>>> 'description': 'test3',
>>> 'stuff': [str(self.name1.id), ],
>>> 'db_id': 0,
>>> })
>>> print("ERRORS --> %s" % testform.errors)
>>> print("FORMS --> %s" % testform)
>>> self.assertTrue(testform.is_valid())
>>> testform.save()
>>> dummy = ExtraStuff.objects.get(description='test3')
>>>
>>> =
>>> $ ./manage.py test issue.tests.test_forms.DispLay
>>> IssueFormTests.test_valid_save2
>>> REAL --> []
>>> In Form --> []
>>> Creating test database for alias 'default'...
>>> System check identified no issues (0 silenced).
>>> START
>>> MOCKED --> [{'id': '1', 'displayname': 'foo1 (bar1)'}, {'id': '2',
>>> 'displayname': 'foo2 (bar2)'}]
>>> ERRORS --> 

Re: Unit testing Multiselect fields not loading as expected

2017-05-08 Thread Tim Graham


This is because you have a module level query at my_choices = [(m['id'], 
m['displayname']) for m in get_my_list()].

There's a documentation warning about this; see the "Finding data from your 
production database when running tests?" note in ​this section [0].

[0] 
https://docs.djangoproject.com/en/dev/topics/testing/overview/#the-test-database

On Sunday, May 7, 2017 at 9:05:09 PM UTC-4, Trevor Woolley wrote:
>
> Further investigation shows this as failing outside of a test scenario, 
> and the "my_choices" is not being updated, unless the server (be that the 
> ./manage.py runserver" or a production apache server) is restarted.
>
> Rgds
> Trevor
>
> On Friday, May 5, 2017 at 3:20:04 PM UTC+10, Trevor Woolley wrote:
>>
>> Hi, when I run a unittest on a form containing a MultipleChoiceField, and 
>> in the unittest I test setting what I think should be a valid field, it 
>> does not pass. It appears that field in question extracts the data is uses 
>> for the test before the test database is created, and actually uses the 
>> production database for the values.
>>
>> The result of the test and the (altered snippets) are below, if anyone 
>> can help I'd be grateful.
>>
>> The below example includes a mock of the data fill function, but there is 
>> no difference in the ultimate response, if the mock setup is not used. If 
>> the production database contains the correct IDs the test passes.
>>
>> Rgds
>> Trevor
>>
>> #
>> # forms.py snippet
>> #
>> # appropriate imports
>>
>> def get_my_list():
>> """ Function to get the complete stuff list for multiselect """
>> result = []
>> my_stuff = Stuff.objects.all()
>> for stuff in my_stuff:
>> displayname = "%s (%s)" % (stuff.name1, stuff.name2)
>> result.append({"id": str(stuff.id), "displayname": displayname})
>> print("REAL --> %s" % result)
>> return sorted(result, key=itemgetter("displayname"))
>>
>>
>> class DispLayIssueForm(forms.Form):
>> """ Class to manage the changes / adds for the extra Stuff model """
>> description = forms.CharField(
>> label='Short Description',
>> max_length=199,
>> strip=True
>> )
>> my_choices = [(m['id'], m['displayname']) for m in get_my_list()]
>> print("In Form --> %s" % my_choices)
>>
>> stuff = forms.MultipleChoiceField(
>> widget=forms.SelectMultiple(attrs={'size': '10'}),
>> choices=my_choices,
>> label="My Stuff",
>> required=False,
>> )
>> db_id = forms.CharField(widget=forms.HiddenInput)
>>
>> def clean(self):
>> """ Form Clean function """
>> # 
>>
>> def save(self):
>> """ Form Save function """
>> # 
>>
>> def update(self):
>> """ Form Update function """
>> # 
>>
>>
>> #
>> # test_forms
>> #
>> # appropriate imports
>> # django.test import TestCase
>>
>>
>> def mocked_get_my_list():
>> """ Mocking the function so that it grabs the test data """
>> result = []
>> my_stuff = Stuff.objects.all()
>> for stuff in my_stuff:
>> displayname = "%s (%s)" % (stuff.name1, stuff.name2)
>> result.append({"id": str(stuff.id), "displayname": displayname})
>> print("MOCKED --> %s" % result)
>> return result
>>
>> class DispLayIssueFormTests(TestCase):
>> """ Class to test the display issue form """
>>
>> def setUp(self):
>> """ Initial setup just creates two stuff entries """
>> self.name1 = create_stuff("foo1", "bar1")
>> self.name2 = create_stuff("foo2", "bar2")
>>
>> def tearDown(self):
>> """ Final tear downs """
>> self.name1.delete()
>> self.name2.delete()
>>
>> # Other tests that leave the stuff fields empty pass
>>
>> @mock.patch('form.get_my_list')
>> def test_valid_save2(self, mock_list):
>> """ Test to ensure a valid save succeeds - with stuff """
>> print("START")
>> mock_list.side_effect = mocked_get_my_list()
>> testform = DispLayIssueForm({
>> 'description': 'test3',
>> 'stuff': [str(self.name1.id), ],
>> 'db_id': 0,
>> })
>> print("ERRORS --> %s" % testform.errors)
>> print("FORMS --> %s" % testform)
>> self.assertTrue(testform.is_valid())
>> testform.save()
>> dummy = ExtraStuff.objects.get(description='test3')
>>
>> =
>> $ ./manage.py test 
>> issue.tests.test_forms.DispLayIssueFormTests.test_valid_save2
>> REAL --> []
>> In Form --> []
>> Creating test database for alias 'default'...
>> System check identified no issues (0 silenced).
>> START
>> MOCKED --> [{'id': '1', 'displayname': 'foo1 (bar1)'}, {'id': '2', 
>> 'displayname': 'foo2 (bar2)'}]
>> ERRORS --> stuff> class="errorlist">Select a valid choice. 1 is not one of the available 
>> choices.
>> FORMS --> > for="id_description">Description:> name="description" value="test3" id="id_description" maxlength="199" 
>> required 

Re: Unit testing Multiselect fields not loading as expected

2017-05-07 Thread Trevor Woolley
Further investigation shows this as failing outside of a test scenario, and 
the "my_choices" is not being updated, unless the server (be that the 
./manage.py runserver" or a production apache server) is restarted.

Rgds
Trevor

On Friday, May 5, 2017 at 3:20:04 PM UTC+10, Trevor Woolley wrote:
>
> Hi, when I run a unittest on a form containing a MultipleChoiceField, and 
> in the unittest I test setting what I think should be a valid field, it 
> does not pass. It appears that field in question extracts the data is uses 
> for the test before the test database is created, and actually uses the 
> production database for the values.
>
> The result of the test and the (altered snippets) are below, if anyone can 
> help I'd be grateful.
>
> The below example includes a mock of the data fill function, but there is 
> no difference in the ultimate response, if the mock setup is not used. If 
> the production database contains the correct IDs the test passes.
>
> Rgds
> Trevor
>
> #
> # forms.py snippet
> #
> # appropriate imports
>
> def get_my_list():
> """ Function to get the complete stuff list for multiselect """
> result = []
> my_stuff = Stuff.objects.all()
> for stuff in my_stuff:
> displayname = "%s (%s)" % (stuff.name1, stuff.name2)
> result.append({"id": str(stuff.id), "displayname": displayname})
> print("REAL --> %s" % result)
> return sorted(result, key=itemgetter("displayname"))
>
>
> class DispLayIssueForm(forms.Form):
> """ Class to manage the changes / adds for the extra Stuff model """
> description = forms.CharField(
> label='Short Description',
> max_length=199,
> strip=True
> )
> my_choices = [(m['id'], m['displayname']) for m in get_my_list()]
> print("In Form --> %s" % my_choices)
>
> stuff = forms.MultipleChoiceField(
> widget=forms.SelectMultiple(attrs={'size': '10'}),
> choices=my_choices,
> label="My Stuff",
> required=False,
> )
> db_id = forms.CharField(widget=forms.HiddenInput)
>
> def clean(self):
> """ Form Clean function """
> # 
>
> def save(self):
> """ Form Save function """
> # 
>
> def update(self):
> """ Form Update function """
> # 
>
>
> #
> # test_forms
> #
> # appropriate imports
> # django.test import TestCase
>
>
> def mocked_get_my_list():
> """ Mocking the function so that it grabs the test data """
> result = []
> my_stuff = Stuff.objects.all()
> for stuff in my_stuff:
> displayname = "%s (%s)" % (stuff.name1, stuff.name2)
> result.append({"id": str(stuff.id), "displayname": displayname})
> print("MOCKED --> %s" % result)
> return result
>
> class DispLayIssueFormTests(TestCase):
> """ Class to test the display issue form """
>
> def setUp(self):
> """ Initial setup just creates two stuff entries """
> self.name1 = create_stuff("foo1", "bar1")
> self.name2 = create_stuff("foo2", "bar2")
>
> def tearDown(self):
> """ Final tear downs """
> self.name1.delete()
> self.name2.delete()
>
> # Other tests that leave the stuff fields empty pass
>
> @mock.patch('form.get_my_list')
> def test_valid_save2(self, mock_list):
> """ Test to ensure a valid save succeeds - with stuff """
> print("START")
> mock_list.side_effect = mocked_get_my_list()
> testform = DispLayIssueForm({
> 'description': 'test3',
> 'stuff': [str(self.name1.id), ],
> 'db_id': 0,
> })
> print("ERRORS --> %s" % testform.errors)
> print("FORMS --> %s" % testform)
> self.assertTrue(testform.is_valid())
> testform.save()
> dummy = ExtraStuff.objects.get(description='test3')
>
> =
> $ ./manage.py test 
> issue.tests.test_forms.DispLayIssueFormTests.test_valid_save2
> REAL --> []
> In Form --> []
> Creating test database for alias 'default'...
> System check identified no issues (0 silenced).
> START
> MOCKED --> [{'id': '1', 'displayname': 'foo1 (bar1)'}, {'id': '2', 
> 'displayname': 'foo2 (bar2)'}]
> ERRORS --> stuffSelect 
> a valid choice. 1 is not one of the available choices.
> FORMS -->  for="id_description">Description: name="description" value="test3" id="id_description" maxlength="199" 
> required />
> Stuff: class="errorlist">Select a valid choice. 1 is not one of the available 
> choices. multiple="multiple"> id="id_db_id" />
> F
> ==
> FAIL: test_valid_save2 (issue.tests.test_forms.DispLayIssueFormTests)
> Test to ensure a valid save succeeds - with stuff
> --
> Traceback (most recent call last):
>   File "c:\projects\issue\lib\site-packages\mock\mock.py", line 1305, in 
> patched
> return func(*args, **keywargs)
>   File 

Unit testing Multiselect fields not loading as expected

2017-05-04 Thread Trevor Woolley
Hi, when I run a unittest on a form containing a MultipleChoiceField, and 
in the unittest I test setting what I think should be a valid field, it 
does not pass. It appears that field in question extracts the data is uses 
for the test before the test database is created, and actually uses the 
production database for the values.

The result of the test and the (altered snippets) are below, if anyone can 
help I'd be grateful.

The below example includes a mock of the data fill function, but there is 
no difference in the ultimate response, if the mock setup is not used. If 
the production database contains the correct IDs the test passes.

Rgds
Trevor

#
# forms.py snippet
#
# appropriate imports

def get_my_list():
""" Function to get the complete stuff list for multiselect """
result = []
my_stuff = Stuff.objects.all()
for stuff in my_stuff:
displayname = "%s (%s)" % (stuff.name1, stuff.name2)
result.append({"id": str(stuff.id), "displayname": displayname})
print("REAL --> %s" % result)
return sorted(result, key=itemgetter("displayname"))


class DispLayIssueForm(forms.Form):
""" Class to manage the changes / adds for the extra Stuff model """
description = forms.CharField(
label='Short Description',
max_length=199,
strip=True
)
my_choices = [(m['id'], m['displayname']) for m in get_my_list()]
print("In Form --> %s" % my_choices)

stuff = forms.MultipleChoiceField(
widget=forms.SelectMultiple(attrs={'size': '10'}),
choices=my_choices,
label="My Stuff",
required=False,
)
db_id = forms.CharField(widget=forms.HiddenInput)

def clean(self):
""" Form Clean function """
# 

def save(self):
""" Form Save function """
# 

def update(self):
""" Form Update function """
# 


#
# test_forms
#
# appropriate imports
# django.test import TestCase


def mocked_get_my_list():
""" Mocking the function so that it grabs the test data """
result = []
my_stuff = Stuff.objects.all()
for stuff in my_stuff:
displayname = "%s (%s)" % (stuff.name1, stuff.name2)
result.append({"id": str(stuff.id), "displayname": displayname})
print("MOCKED --> %s" % result)
return result

class DispLayIssueFormTests(TestCase):
""" Class to test the display issue form """

def setUp(self):
""" Initial setup just creates two stuff entries """
self.name1 = create_stuff("foo1", "bar1")
self.name2 = create_stuff("foo2", "bar2")

def tearDown(self):
""" Final tear downs """
self.name1.delete()
self.name2.delete()

# Other tests that leave the stuff fields empty pass

@mock.patch('form.get_my_list')
def test_valid_save2(self, mock_list):
""" Test to ensure a valid save succeeds - with stuff """
print("START")
mock_list.side_effect = mocked_get_my_list()
testform = DispLayIssueForm({
'description': 'test3',
'stuff': [str(self.name1.id), ],
'db_id': 0,
})
print("ERRORS --> %s" % testform.errors)
print("FORMS --> %s" % testform)
self.assertTrue(testform.is_valid())
testform.save()
dummy = ExtraStuff.objects.get(description='test3')

=
$ ./manage.py test 
issue.tests.test_forms.DispLayIssueFormTests.test_valid_save2
REAL --> []
In Form --> []
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
START
MOCKED --> [{'id': '1', 'displayname': 'foo1 (bar1)'}, {'id': '2', 
'displayname': 'foo2 (bar2)'}]
ERRORS --> stuffSelect 
a valid choice. 1 is not one of the available choices.
FORMS --> Description:
Stuff:Select a valid choice. 1 is not one of the available 
choices.
F
==
FAIL: test_valid_save2 (issue.tests.test_forms.DispLayIssueFormTests)
Test to ensure a valid save succeeds - with stuff
--
Traceback (most recent call last):
  File "c:\projects\issue\lib\site-packages\mock\mock.py", line 1305, in 
patched
return func(*args, **keywargs)
  File "c:\projects\issue\issue\tests\test_forms.py", line 288, in 
test_valid_save2
self.assertTrue(testform.is_valid())
AssertionError: False is not true

--
Ran 1 test in 0.538s

FAILED (failures=1)
Destroying test database for alias 'default'...
$ ./manage.py shell
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import django
>>> django.get_version()
'1.11'
>>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop 

Re: Unit testing in django for django template

2016-10-12 Thread ludovic coues
Personally, I use lxml to check the presence of HTML element based on
xpath. Here is an exemple of how I do it:

from django.core.urlresolvers import reverse
from django.test import TestCase
from lxml import etree

class UserUrlTestCase(TestCase):
""" Test for the user app """

def test_login_view(self):
""" The view display a form with username and password fields """
rep = self.client.get(reverse('user:login'))
# No need to continue if we don't get a 200 OK
self.assertEqual(rep.status_code, 200)
# Use xpath to check presence of element
doc = etree.HTML(rep.content)
self.assertEqual(len(doc.findall('.//input[@name="username"]')), 1)
self.assertEqual(len(doc.findall('.//input[@name="password"]')), 1)


You'll need to install the package lxml for the import to work

2016-10-12 22:23 GMT+02:00 James Schneider <jrschneide...@gmail.com>:
> In general, you would request the page and inspect the rendered output.
>
> https://docs.djangoproject.com/en/1.10/topics/testing/tools/#testing-responses
>
> -James
>
> On Wed, Oct 12, 2016 at 12:17 PM, <codemaster...@gmail.com> wrote:
>>
>>  How to Unit testing in django for django  template
>>
>>   please any one help me???
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/c09dfbd9-82d3-4d08-832d-c1e00f78aeed%40googlegroups.com.
>> For more options, visit https://groups.google.com/d/optout.
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWuP9jO5f3VExVduCLck2wPAaCtEkXKa%2B%3DTgmLEVd8E5g%40mail.gmail.com.
>
> For more options, visit https://groups.google.com/d/optout.



-- 

Cordialement, Coues Ludovic
+336 148 743 42

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEuG%2BTaiByfaWQ1-C545PooEEtNL0FB6B3g2uWxb84Hz%3DqD4Rw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing in django for django template

2016-10-12 Thread James Schneider
In general, you would request the page and inspect the rendered output.

https://docs.djangoproject.com/en/1.10/topics/testing/tools/#testing-responses

-James

On Wed, Oct 12, 2016 at 12:17 PM, <codemaster...@gmail.com> wrote:

>  How to Unit testing in django for django  template
>
>   please any one help me???
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/c09dfbd9-82d3-4d08-832d-c1e00f78aeed%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/c09dfbd9-82d3-4d08-832d-c1e00f78aeed%40googlegroups.com?utm_medium=email_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWuP9jO5f3VExVduCLck2wPAaCtEkXKa%2B%3DTgmLEVd8E5g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Unit testing in django for django template

2016-10-12 Thread codemaster472
 How to Unit testing in django for django  template

  please any one help me???

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c09dfbd9-82d3-4d08-832d-c1e00f78aeed%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How do you approach unit testing for pluggable apps?

2015-12-21 Thread Nan
So far I usually just build a sample project that also serves as a 
demonstration of how to use the pluggable app, and use `manage.py test` to 
run the tests inside the pluggable apps test module.  Is this the preferred 
method?  Should a pluggable app's tests stand alone and be runnable outside 
of project context?  If so, how would you handle testing operations that 
require database access?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5dcb2d3b-0e56-44a9-92f1-d857ff9423a6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing for apis

2015-11-24 Thread David Palao
Hi,
I was browsing the EuroPython 2015 videos and found a talk titled "TDD
for APIs". I have not watched it, but you might be interested in it:
https://www.youtube.com/watch?v=Okz6agNgaTA=51=PL8uoeex94UhGGUH0mFb-StlZ1WYGWiJfP
Best

2015-11-24 11:27 GMT+01:00 Kishan Mehta <kishanmeh...@gmail.com>:
> Hi All,
>
> How can I write negative unit test cases for api endpoints
> I am using django.tests.TestCase for unit testing.
>
> Thanks,
> Kishan
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/d67330b4-e495-4ae3-9898-2d9d980ec6e4%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAKUKWz%3D3NreQyh1eCfnwSqy0AcOuESR3mo9gvdbj%3D4L3thJL8Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Unit testing for apis

2015-11-24 Thread Kishan Mehta
Hi All,

How can I write negative unit test cases for api endpoints 
I am using django.tests.TestCase for unit testing. 

Thanks,
Kishan

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d67330b4-e495-4ae3-9898-2d9d980ec6e4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit-testing Custom Admin Action, requires request and querysets parameters.

2014-11-25 Thread Azam Alias
Hi Collin,

I apologise for the late update. Didnt get any notifications from your 
reply.

I have solved this issue as per your suggestion. Pasting the solution for 
others' reference. 

Thanks !

from django.test import TestCase
from django.contrib.admin.sites import AdminSite
from batch_apps.models import App
from batch_apps.admin import AppAdmin


class MockRequest(object):
pass

request = MockRequest()


class AppAdminTest(TestCase):

def setUp(self):
self.app_admin = AppAdmin(App, AdminSite())

def test_activate_apps_should_activate_inactive_app(self):
app1 = App.objects.create(name='Inactive App 001', is_active=False)
queryset = App.objects.filter(pk=1)
self.app_admin.activate_apps(request, queryset)
self.assertTrue(App.objects.get(pk=1).is_active)

def test_deactivate_apps_should_deactivate_active_app(self):
app1 = App.objects.create(name='Active App 001', is_active=True)
queryset = App.objects.filter(pk=1)
self.app_admin.deactivate_apps(request, queryset)
self.assertFalse(App.objects.get(pk=1).is_active)



On Thursday, 6 November 2014 01:05:13 UTC+8, Collin Anderson wrote:
>
> Hello,
>
> Would it work to import AppAdmin, instantiate it, and then call the 
> methods in a unit test?
>
> Collin
>  
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2f79f583-99a9-4d1c-b384-9733bbf98ec0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit-testing Custom Admin Action, requires request and querysets parameters.

2014-11-05 Thread Collin Anderson
Hello,

Would it work to import AppAdmin, instantiate it, and then call the methods 
in a unit test?

Collin
 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9338e316-a58c-4ec1-a67a-47c52ffba1bc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Unit-testing Custom Admin Action, requires request and querysets parameters.

2014-11-02 Thread Azam Alias
Hi, 

I would like to unit-test the activate_apps( ) and deactivate_apps( ) 
functions below, as low-level as possible.

How could I do this without going through Selenium (FT) route?

In my admin.py:

from django.contrib import admin
from my_app_listing.models import App

class AppAdmin(admin.ModelAdmin):
actions = ['activate_apps', 'deactivate_apps']
list_display = ('name', 'is_active', 'frequency')
fieldsets = [
(None, {'fields': ['name']}),
(None, {'fields': ['is_active']}),
(None, {'fields': ['frequency']}),
('Description', {'fields': ['description'], 'classes': ['collapse'
]}),
]

def activate_apps(self, request, queryset):
queryset.update(is_active=True)
activate_apps.short_description = "Activate selected Apps"

def deactivate_apps(self, request, queryset):
queryset.update(is_active=False)
deactivate_apps.short_description = "Deactivate selected Apps"

admin.site.register(App, AppAdmin)

Thanks in advance

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/bea4fcab-8d7c-4613-9454-f5a70181ce5a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing - self.assertEqual("Break it!", resp.content)

2014-07-07 Thread Pepsodent Cola
Hi,
I have been using assertEqual lately in my unit testing to deliberately 
make coverage break.  By comparing *Something False* with the 
complete HTML returned (*resp.content*).

self.assertEqual("Something False", *resp.content*)

In order to reveal and debug these 3 links.

self.assertNotContains(resp, 'Documentation')
self.assertNotContains(resp, 'Change 
password')
self.assertNotContains(resp, 'Log out')


But the unit test debug output of the complete HTML returned doesn't reveal 
those 3 links.  Why is that?

unit test output
http://dpaste.com/23XGR4M.txt

Compared to the HTML returned that I can see by manually checking the 
source page from my browser.

html source page
http://dpaste.com/0PCZJ0D

 Welcome, joe. 


*Documentation / Change password / Log out *



Is there something wrong with my overridden template file?  Where I have 
removed *{% block userlinks %}* in order to reveal Django admins above 3 
default links.

password_reset_form.html
http://dpaste.com/0T3N3JK

{% extends "admin/base_site.html" %}
{% load i18n %}





*{% comment %}{% block userlinks %}{% trans "Change password" %} / {% trans "Log out" %}{% endblock %}{% 
endcomment %}*


{% comment %}
{% block breadcrumbs %}

{% trans "Home" %}
 {% trans "Password reset" %}

{% endblock %}
{% endcomment %}

{% block title %}{% trans "Password reset - v.2" %}{% endblock %}


{% block content %}
{% trans "Password reset" %}
{% trans "Forgotten your password? Enter your email address below, and 
we'll email instructions for setting a new one." %}

{% csrf_token %}
{{ form.email.errors }}
{% trans "Email address:" %} {{ form.email 
}} 

{% endblock %}












On Monday, July 7, 2014 6:08:20 AM UTC+2, mitesh_django wrote:
>
> Hi,
>
> You are trying to compare  break it!  with the complete HTML 
> returned. Instead of assertEqual, use assertIn.
>
> self.assertIn("Break it!", resp.content)
>
> Regards, 
> Mitesh
> On 7 Jul 2014 01:44, "Pepsodent Cola" <pepsod...@gmail.com > 
> wrote:
>
>> When I run this unit test to make it break so it can output a bunch of 
>> html data.
>>
>> self.assertEqual("Break it!", *resp.content*)
>>
>>
>> test.py
>> # Reset password no login
>>
>> def test_Reset_no_login(self):
>> self.assertTrue(isinstance(self.user, User))
>> login = self.client.login(username='captain', password='america')
>>
>> self.assertEqual("Profile", *resp.content*)
>>
>> self.assertNotContains(resp, '> href="/admin/doc/">Documentation')
>> self.assertNotContains(resp, '> href="/admin/password_change/">Change password')
>> self.assertNotContains(resp, 'Log out')
>>
>>
>>
>> Then I can't find these html tags in unit test's *resp.content* but when 
>> I manually check the html source page from the web browser then I see those 
>> 3 html tags.
>> Why isn't unit test *resp.content* output displaying these 3 html lines?
>>
>>
>> html source page
>> http://dpaste.com/0PCZJ0D
>>
>>  Welcome, joe. 
>>
>>
>> *Documentation / > href="/admin/password_change/">Change password / > href="/admin/logout/">Log out *
>> 
>>
>>
>> unit test output
>> http://dpaste.com/23XGR4M.txt
>>
>> ==
>> FAIL: test_Reset_no_login (userprofile.tests.PasswordResetTest)
>> --
>> Traceback (most recent call last):
>>   File "/home/Python/Projects/Navi/Django/navi/userprofile/tests.py", 
>> line 132, in test_Reset_no_login
>>
>> self.assertEqual("Profile", resp.content)
>>
>> AssertionError: 'Profile' != '\n> lang="en-us" >\n\nPassword reset - v.2\n> rel="stylesheet" type="text/css" href="/static/admin/css/base.css" 
>> />\n\n\n\n> type="text/javascript">window.__admin_media_prefix__ = 
>> "/static/admin/";\n\n> />\n\n\n\n\n\n\n> id="container">\n\n\n\n> id="header">\n\n\n> id="site-name">Navi administration - v.1\n\n\n
>> \nAdmin navigation\n\n\n
>> \n\nHome\n\n
>> \n\n\n\n\n\n\n\n\n
>> \n\n\n\nPassword 
>> reset\nForgotten your password? Enter your email address below, and 
>> we\'ll email instructions for set

Re: Unit testing - self.assertEqual("Break it!", resp.content)

2014-07-06 Thread Mitesh Patel
Hi,

You are trying to compare  break it!  with the complete HTML
returned. Instead of assertEqual, use assertIn.

self.assertIn("Break it!", resp.content)

Regards,
Mitesh
On 7 Jul 2014 01:44, "Pepsodent Cola"  wrote:

> When I run this unit test to make it break so it can output a bunch of
> html data.
>
> self.assertEqual("Break it!", *resp.content*)
>
>
> test.py
> # Reset password no login
>
> def test_Reset_no_login(self):
> self.assertTrue(isinstance(self.user, User))
> login = self.client.login(username='captain', password='america')
>
> self.assertEqual("Profile", *resp.content*)
>
> self.assertNotContains(resp, 'Documentation')
> self.assertNotContains(resp, 'Change
> password')
> self.assertNotContains(resp, 'Log out')
>
>
>
> Then I can't find these html tags in unit test's *resp.content* but when
> I manually check the html source page from the web browser then I see those
> 3 html tags.
> Why isn't unit test *resp.content* output displaying these 3 html lines?
>
>
> html source page
> http://dpaste.com/0PCZJ0D
>
>  Welcome, joe.
>
>
> *Documentation /  href="/admin/password_change/">Change password /  href="/admin/logout/">Log out *
> 
>
>
> unit test output
> http://dpaste.com/23XGR4M.txt
>
> ==
> FAIL: test_Reset_no_login (userprofile.tests.PasswordResetTest)
> --
> Traceback (most recent call last):
>   File "/home/Python/Projects/Navi/Django/navi/userprofile/tests.py", line
> 132, in test_Reset_no_login
>
> self.assertEqual("Profile", resp.content)
>
> AssertionError: 'Profile' != '\n >\n\nPassword reset - v.2\n type="text/css" href="/static/admin/css/base.css" />\n\n\n\n type="text/javascript">window.__admin_media_prefix__ =
> "/static/admin/";\n\n />\n\n\n\n\n\n\n id="container">\n\n\n\n id="header">\n\n\n id="site-name">Navi administration - v.1\n\n\n
> \nAdmin navigation\n\n\n
> \n\nHome\n\n
> \n\n\n\n\n\n\n\n\n
> \n\n\n\nPassword
> reset\nForgotten your password? Enter your email address below, and
> we\'ll email instructions for setting a new one.\n\n method="post"> value=\'iXJku3wGmCRg95SlHqC5QfHEH48XCRRZ\' />\n\n for="id_email">Email address:  name="email" type="text" />  />\n\n\n\n\n\n
> \n\n\n\n\n\n\n\n'
>
> --
> Ran 36 tests in 5.981s
>
> FAILED (failures=1)
> Destroying test database for alias 'default' (':memory:')...
>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/c20a58c5-fad3-4ba6-906e-ca99158f9db6%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAD3RGrSygOn%3D_J2hmMFB87QezLwZSMNfLoN27WL5fwHjvKwi%3Dg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Unit testing - self.assertEqual("Break it!", resp.content)

2014-07-06 Thread Pepsodent Cola
When I run this unit test to make it break so it can output a bunch of html 
data.

self.assertEqual("Break it!", *resp.content*)


test.py
# Reset password no login

def test_Reset_no_login(self):
self.assertTrue(isinstance(self.user, User))
login = self.client.login(username='captain', password='america')

self.assertEqual("Profile", *resp.content*)

self.assertNotContains(resp, 'Documentation')
self.assertNotContains(resp, 'Change 
password')
self.assertNotContains(resp, 'Log out')



Then I can't find these html tags in unit test's *resp.content* but when I 
manually check the html source page from the web browser then I see those 3 
html tags.
Why isn't unit test *resp.content* output displaying these 3 html lines?


html source page
http://dpaste.com/0PCZJ0D

 Welcome, joe. 


*Documentation / Change password / Log out *



unit test output
http://dpaste.com/23XGR4M.txt

==
FAIL: test_Reset_no_login (userprofile.tests.PasswordResetTest)
--
Traceback (most recent call last):
  File "/home/Python/Projects/Navi/Django/navi/userprofile/tests.py", line 
132, in test_Reset_no_login

self.assertEqual("Profile", resp.content)

AssertionError: 'Profile' != '\n\n\nPassword reset - v.2\n\n\n\n\nwindow.__admin_media_prefix__ = 
"/static/admin/";\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nNavi administration - v.1\n\n\n
\nAdmin navigation\n\n\n
\n\nHome\n\n
\n\n\n\n\n\n\n\n\n
\n\n\n\nPassword 
reset\nForgotten your password? Enter your email address below, and 
we\'ll email instructions for setting a new one.\n\n\n\nEmail address:  \n\n\n\n\n\n
\n\n\n\n\n\n\n\n'

--
Ran 36 tests in 5.981s

FAILED (failures=1)
Destroying test database for alias 'default' (':memory:')...


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c20a58c5-fad3-4ba6-906e-ca99158f9db6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Unit testing - return HttpResponseRedirect('/accounts/loggedin')

2014-07-04 Thread Pepsodent Cola
Hi coverage has highlighted that I have no unit test for the line, 
regarding *HttpResponseRedirect('/accounts/loggedin')*.
How can I write a test that makes Coverage happy regarding this?


views.py

def auth_view(request): 
username = request.POST.get('username', '') 
password = request.POST.get('password', '') 
user = auth.authenticate(username=username, password=password) 

if user is not None: 
auth.login(request, user)   
return HttpResponseRedirect('*/accounts/loggedin*')   
else:
return HttpResponseRedirect('/accounts/invalid') 
#___

def loggedin(request):
return render_to_response('loggedin.html',
   {'full_name': 
request.user.username})
#___

def invalid_login(request):
return render_to_response('invalid_login.html')
#___




url.py

# user auth urls
url(r'^accounts/login/$', 'navi.views.login'),
url(r'^accounts/auth/$', 'navi.views.*auth_view*'),
url(r'^accounts/logout/$', 'navi.views.logout'),
url(r'^accounts/loggedin/$', 'navi.views.loggedin'),
url(r'^accounts/invalid/$', 'navi.views.invalid_login'),



test.py

###
#Forms
###

class FormTest(TestCase):
# Create User
def setUp(self):
self.user = User.objects.create_user(username='captain', 
password='america')

# Logged in
def test_Logged_in(self):
self.assertTrue(isinstance(self.user, User))
login = self.client.login(username='captain', password='america')
self.assertEqual(login, True)

resp = self.client.get('/accounts/profile/')
#  resp = self.client.get(reverse('userprofile:user_profile'))
self.assertEqual(resp.status_code, 200)

#  resp = self.client.post('/accounts/profile/', {'username':'captain', 
'password':'america'}, follow=True)
resp = self.client.post('/accounts/profile/', follow=True)
self.assertEqual(resp.status_code, 200)

resp = self.client.get('/accounts/fakepage/')
resp = self.client.get('/accounts/loggedin/')


# Invalid login
def test_Invalid_login(self):
resp = self.client.get('/accounts/profile/', follow=True)
self.assertEqual(resp.status_code, 200)
self.assertRedirects(resp, 
'/accounts/login/?next=/accounts/profile/')

self.assertTrue(isinstance(self.user, User))
login = self.client.login(username='captain', password='america')
self.assertEqual(login, True)
resp = self.client.get(reverse('userprofile:user_profile'), 
follow=True)
self.assertEqual(resp.status_code, 200)

#  resp = self.client.post('/accounts/profile/', {'username':'captain', 
'password':'america'}, follow=True)
resp = self.client.post('/accounts/profile/', follow=True)
self.assertEqual(resp.status_code, 200)


class AuthTest(TestCase):
def test_auth_view(self):
resp = self.client.get('/accounts/auth/', follow=True)
self.assertEqual(resp.status_code, 200)
self.assertRedirects(resp, '/accounts/invalid/')

def test_loggedin(self):
resp = self.client.post('/accounts/loggedin/')
self.assertEqual(resp.status_code, 200)

def test_logout(self):
resp = self.client.get('/accounts/logout/')
self.assertEqual(resp.status_code, 200)
#___



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3528b26d-52f9-4e26-aaab-631e955936e6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing - self.assertEqual(login, True)

2014-07-03 Thread Pepsodent Cola
Thanks!  I see what I did wrong now.


class UserProfileTest(TestCase):
# Create User
def setUp(self):
self.user = *User.objects.create_user*(username='captain', 
password='america')

# Logged in
def test_VIEW_USER__Logged_in(self):
self.assertTrue(isinstance(self.user, User))
login = self.client.login(username='captain', password='america')
self.assertEqual(login, True)



https://docs.djangoproject.com/en/1.5/intro/tutorial05/#testing-our-new-view

class UserProfileTest(TestCase):
*# User factory method*
def create_user(self, username='joe', password='joe'):
return *User.objects.create*(username=username, password=password)

# Create User
def test_creation_USER(self):
u = self.create_user()
self.assertTrue(isinstance(u, User))
login = self.client.login(username='joe', password='joe')
self.assertEqual(login, True)






On Thursday, July 3, 2014 2:57:24 PM UTC+2, Amim Knabben wrote:
>
> duplicated question
>
> https://groups.google.com/forum/#!topic/django-users/I4wmYKNMNn8
>
>
> On Thu, Jul 3, 2014 at 9:09 AM, Pepsodent Cola  > wrote:
>
>> I want to run a unit test for a user logging in but I get error.  What am 
>> I doing wrong?
>>
>>
>> from django.test import TestCase
>> from userprofile.models import UserProfile
>> from django.contrib.auth.models import User
>>
>> class UserProfileTest(TestCase):
>> # User factory method
>> def create_user(self, username='joe', password='joe'):
>> return User.objects.create(username=username, password=password)
>>
>> # Create User
>> def test_creation_USER(self):
>> u = self.create_user()
>> self.assertTrue(isinstance(u, User))
>> login = self.client.login(username='joe', password='joe')
>> *self.assertEqual(login, True)*
>>
>> ==
>> FAIL: test_creation_USER (userprofile.tests.UserProfileTest)
>> --
>> Traceback (most recent call last):
>>   File "/home/Django/project/userprofile/tests.py", line 44, in 
>> test_creation_USER
>> self.assertEqual(login, True)
>> *AssertionError: False != True*
>>
>> --
>>
>>
>>  -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at http://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/5d49c776-fe1f-4702-abc1-d2c99468d82a%40googlegroups.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
>
> -- 
>
> *AMIM KNABBEN*
> +55 48 9680 9126 (m)
>
>  

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9974fc0b-a1ec-4048-9a24-3773b9f3540d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit testing - self.assertEqual(login, True)

2014-07-03 Thread Amim Knabben
duplicated question

https://groups.google.com/forum/#!topic/django-users/I4wmYKNMNn8


On Thu, Jul 3, 2014 at 9:09 AM, Pepsodent Cola 
wrote:

> I want to run a unit test for a user logging in but I get error.  What am
> I doing wrong?
>
>
> from django.test import TestCase
> from userprofile.models import UserProfile
> from django.contrib.auth.models import User
>
> class UserProfileTest(TestCase):
> # User factory method
> def create_user(self, username='joe', password='joe'):
> return User.objects.create(username=username, password=password)
>
> # Create User
> def test_creation_USER(self):
> u = self.create_user()
> self.assertTrue(isinstance(u, User))
> login = self.client.login(username='joe', password='joe')
> *self.assertEqual(login, True)*
>
> ==
> FAIL: test_creation_USER (userprofile.tests.UserProfileTest)
> --
> Traceback (most recent call last):
>   File "/home/Django/project/userprofile/tests.py", line 44, in
> test_creation_USER
> self.assertEqual(login, True)
> *AssertionError: False != True*
>
> --
>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/5d49c776-fe1f-4702-abc1-d2c99468d82a%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 

*AMIM KNABBEN*
+55 48 9680 9126 (m)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAODc%2BXaWUytkQGo1PCrRkE4zLzc-TM0P4cdC%3Dxf8bK8%3DCMNgPA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Unit testing - self.assertEqual(login, True)

2014-07-03 Thread Pepsodent Cola
I want to run a unit test for a user logging in but I get error.  What am I 
doing wrong?


from django.test import TestCase
from userprofile.models import UserProfile
from django.contrib.auth.models import User

class UserProfileTest(TestCase):
# User factory method
def create_user(self, username='joe', password='joe'):
return User.objects.create(username=username, password=password)

# Create User
def test_creation_USER(self):
u = self.create_user()
self.assertTrue(isinstance(u, User))
login = self.client.login(username='joe', password='joe')
*self.assertEqual(login, True)*

==
FAIL: test_creation_USER (userprofile.tests.UserProfileTest)
--
Traceback (most recent call last):
  File "/home/Django/project/userprofile/tests.py", line 44, in 
test_creation_USER
self.assertEqual(login, True)
*AssertionError: False != True*

--


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5d49c776-fe1f-4702-abc1-d2c99468d82a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: unit testing

2013-07-09 Thread ben
Also note that Django 1.6 will bring a better test discovery mechanism. See 
the full details at 
https://docs.djangoproject.com/en/dev/releases/1.6/#discovery-of-tests-in-any-test-module

Django 1.6 ships with a new test runner that allows more flexibility in the 
> location of tests. The previous runner (
> django.test.simple.DjangoTestSuiteRunner) found tests only in the 
> models.py and tests.py modules of a Python package 
> inINSTALLED_APPS
> .
> The new runner (django.test.runner.DiscoverRunner) uses the test 
> discovery features built into unittest2 (the version of unittestin the 
> Python 2.7+ standard library, and bundled with Django). With test 
> discovery, tests can be located in any module whose name matches the 
> pattern test*.py.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: unit testing

2013-07-08 Thread Larry Martell
On Mon, Jul 8, 2013 at 9:36 AM, Javier Guerra Giraldez
 wrote:
> On Mon, Jul 8, 2013 at 10:13 AM, Larry Martell  
> wrote:
>> I had seen the __init__ but I thought the tests had to be in the same
>> dir as the models file.
>
>
> the tests _module_ has to be in the same dir as the models module.
> that means either a tests.py file, or a tests directory with an
> __init__.py file in it.

Thanks for the clarification.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: unit testing

2013-07-08 Thread Javier Guerra Giraldez
On Mon, Jul 8, 2013 at 10:13 AM, Larry Martell  wrote:
> I had seen the __init__ but I thought the tests had to be in the same
> dir as the models file.


the tests _module_ has to be in the same dir as the models module.
that means either a tests.py file, or a tests directory with an
__init__.py file in it.

--
Javier

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: unit testing

2013-07-08 Thread Larry Martell
On Mon, Jul 8, 2013 at 8:59 AM,   wrote:
>
>
> On Monday, July 8, 2013 7:49:53 AM UTC-4, larry@gmail.com wrote:
>>
>>
>>
>> Ah, I missed that in the docs. Thanks. When I renamed it to tests.py
>> it got picked up.
>>
>> But in the django/contrib dirs (e.g. django/contrib/auth) the tests
>> are in a tests sub dir and are not called tests.py and they seem to
>> get run.
>
>
> Django will run all tests imported from the tests module. Check out the
> __init__.py in django/contrib/auth/tests and you'll see it imports all of
> the tests from the other files in the test dir.

I had seen the __init__ but I thought the tests had to be in the same
dir as the models file.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: unit testing

2013-07-08 Thread ben


On Monday, July 8, 2013 7:49:53 AM UTC-4, larry@gmail.com wrote:
>
>
>
> Ah, I missed that in the docs. Thanks. When I renamed it to tests.py 
> it got picked up. 
>
> But in the django/contrib dirs (e.g. django/contrib/auth) the tests 
> are in a tests sub dir and are not called tests.py and they seem to 
> get run. 
>

Django will run all tests imported from the tests module. Check out the 
__init__.py in django/contrib/auth/tests and you'll see it imports all of 
the tests from the other files in the test dir.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: unit testing

2013-07-08 Thread Larry Martell
On Sun, Jul 7, 2013 at 10:05 PM, Javier Guerra Giraldez
 wrote:
> On Sun, Jul 7, 2013 at 10:47 PM, Larry Martell  
> wrote:
>> MeasDataTest is declared as:
>>
>> class MeasDataTest(TestCase):
>>
>> Why do I get "does not refer to a test"?
>
> where do you define your test?  AFAIR, it must be either in the
> models.py, or a tests.py file in the same directory.

Ah, I missed that in the docs. Thanks. When I renamed it to tests.py
it got picked up.

But in the django/contrib dirs (e.g. django/contrib/auth) the tests
are in a tests sub dir and are not called tests.py and they seem to
get run.

>
>> Then I tried:
>>
>> $ python manage.py test cdsem
>> Failed to install custom SQL for cdsem.Tool model: (1054, "Unknown
>> column 'category' in 'field list'")
>
> are you using custom SQL?

There was a .sql file in a sql dir that I hadn't noticed. It was a few
years ago before I was working on this app and it was no longer
applicable so I removed it. Thanks again.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: unit testing

2013-07-07 Thread Javier Guerra Giraldez
On Sun, Jul 7, 2013 at 10:47 PM, Larry Martell  wrote:
> MeasDataTest is declared as:
>
> class MeasDataTest(TestCase):
>
> Why do I get "does not refer to a test"?

where do you define your test?  AFAIR, it must be either in the
models.py, or a tests.py file in the same directory.


> Then I tried:
>
> $ python manage.py test cdsem
> Failed to install custom SQL for cdsem.Tool model: (1054, "Unknown
> column 'category' in 'field list'")

are you using custom SQL?

in your Tool model, the field 'category' is a ForeignKey, by default,
this defines a 'category_id' field in the database, not 'category'.

--
Javier

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: unit testing

2013-07-07 Thread Larry Martell
On Sun, Jul 7, 2013 at 7:22 PM, Larry Martell <larry.mart...@gmail.com> wrote:
> Just getting started with django unit testing. I created a very simple
> test, just to see how things work. Here is my test:
>
> from django.test import TestCase
>
> fixtures = ['auth_user', 'auth_permission', 'data_cst']
>
> class MeasDataTest(TestCase):
> def test_MeasDate(self):
> # login
> response = self.client.post('/accounts/login//', {'username':
> 'admin', 'password': 'x'})
> self.assertEqual(response.status_code, 200)
>
>
> I ran 'python manage.py test' and got this output:
>
> Creating test database for alias 'default'...
> FE.Starting
> batch of 1 tasks
> MockRunnerKWArgs @ 2013-07-07 18:49:43.663905
> {"value": 5}
>   Completed in 0.04 seconds
>   0.0421 seconds per task on average
>   1 tasks succeeded (100.0% success rate)
>
> Dispatched 1 tasks in 0.0916 seconds using 1 process.
> Average time per task is 0.0916 seconds
> .Starting batch of 1 tasks
> MockRunnerB @ 2013-07-07 18:49:51.635251
>
>   Completed in 0.03 seconds
>   0.0270 seconds per task on average
>   1 tasks succeeded (100.0% success rate)
>   Remaining tasks: 1
>
> Starting batch of 1 tasks
> MockRunnerC @ 2013-07-07 18:49:51.655887
>
>   Completed in 0.02 seconds
>   0.0200 seconds per task on average
>   1 tasks succeeded (100.0% success rate)
>
> Dispatched 2 tasks in 0.0486 seconds using 1 process.
> Average time per task is 0.0243 seconds
> .Starting batch of 1 tasks
> MockRunnerA @ 2013-07-07 18:49:59.659529
>
>   Completed in 0.03 seconds
>   0.0340 seconds per task on average
>   1 tasks succeeded (100.0% success rate)
>
> Dispatched 1 tasks in 0.0360 seconds using 1 process.
> Average time per task is 0.0360 seconds
> .Dispatched 0 tasks in 0.0017 seconds using 1 process.
> s...
> ==
> ERROR: test_site_profile_not_available
> (django.contrib.auth.tests.models.ProfileTestCase)
> --
> Traceback (most recent call last):
>   File 
> "/Library/Python/2.7/site-packages/django/contrib/auth/tests/models.py",
> line 29, in test_site_profile_not_available
> del settings.AUTH_PROFILE_MODULE
>   File "/Library/Python/2.7/site-packages/django/utils/functional.py",
> line 215, in __delattr__
> delattr(self._wrapped, name)
> AttributeError: AUTH_PROFILE_MODULE
>
> ==
> FAIL: test_message_attrs
> (django.contrib.auth.tests.context_processors.AuthContextProcessorTests)
> --
> Traceback (most recent call last):
>   File 
> "/Library/Python/2.7/site-packages/django/contrib/auth/tests/context_processors.py",
> line 58, in test_message_attrs
> self.assertContains(response, "Message 1")
>   File "/Library/Python/2.7/site-packages/django/test/testcases.py",
> line 637, in assertContains
> msg_prefix + "Couldn't find '%s' in response" % text)
> AssertionError: Couldn't find 'Message 1' in response
>
> --
> Ran 350 tests in 2354.881s
>
> FAILED (failures=1, errors=1, skipped=1)
> Destroying test database for alias 'default'...
>
> But it never ran my tests.
>
> Questions:

I've figured out some of this myself.

>
> -What are the lines with the dots and F, E, and s?

It appears each dot is a passed test and the F, E, and s are Failed,
Error, and skipped. Is that is in the docs anywhere?

> -What are the 350 tests it ran?

The tests it's running appear to be the django tests from the contrib
dirs that are in my INSTALLED_APPS (auth, contenttypes, sessions,
sites, admin, and staticfiles).

Why does it only print info on a few tests if it's running 350? Why is
there 1 failure, 1 error and 1 skipped? Shouldn't all the contrib
tests pass?

> -Why didn't it run my test?

Putting that aside for now, I specified my test on the command line:

$ python manage.py test cdsem.MeasDataTest
ValueError: Test label 'cdsem.MeasDataTest' does not refer to a test

MeasDataTest is declared as:

class MeasDataTest(TestCase):

Why do I get "does not refer to a test"?

Then I tried:

$ p

unit testing

2013-07-07 Thread Larry Martell
Just getting started with django unit testing. I created a very simple
test, just to see how things work. Here is my test:

from django.test import TestCase

fixtures = ['auth_user', 'auth_permission', 'data_cst']

class MeasDataTest(TestCase):
def test_MeasDate(self):
# login
response = self.client.post('/accounts/login//', {'username':
'admin', 'password': 'x'})
self.assertEqual(response.status_code, 200)


I ran 'python manage.py test' and got this output:

Creating test database for alias 'default'...
FE.Starting
batch of 1 tasks
MockRunnerKWArgs @ 2013-07-07 18:49:43.663905
{"value": 5}
  Completed in 0.04 seconds
  0.0421 seconds per task on average
  1 tasks succeeded (100.0% success rate)

Dispatched 1 tasks in 0.0916 seconds using 1 process.
Average time per task is 0.0916 seconds
.Starting batch of 1 tasks
MockRunnerB @ 2013-07-07 18:49:51.635251

  Completed in 0.03 seconds
  0.0270 seconds per task on average
  1 tasks succeeded (100.0% success rate)
  Remaining tasks: 1

Starting batch of 1 tasks
MockRunnerC @ 2013-07-07 18:49:51.655887

  Completed in 0.02 seconds
  0.0200 seconds per task on average
  1 tasks succeeded (100.0% success rate)

Dispatched 2 tasks in 0.0486 seconds using 1 process.
Average time per task is 0.0243 seconds
.Starting batch of 1 tasks
MockRunnerA @ 2013-07-07 18:49:59.659529

  Completed in 0.03 seconds
  0.0340 seconds per task on average
  1 tasks succeeded (100.0% success rate)

Dispatched 1 tasks in 0.0360 seconds using 1 process.
Average time per task is 0.0360 seconds
.Dispatched 0 tasks in 0.0017 seconds using 1 process.
s...
==
ERROR: test_site_profile_not_available
(django.contrib.auth.tests.models.ProfileTestCase)
--
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/contrib/auth/tests/models.py",
line 29, in test_site_profile_not_available
del settings.AUTH_PROFILE_MODULE
  File "/Library/Python/2.7/site-packages/django/utils/functional.py",
line 215, in __delattr__
delattr(self._wrapped, name)
AttributeError: AUTH_PROFILE_MODULE

==
FAIL: test_message_attrs
(django.contrib.auth.tests.context_processors.AuthContextProcessorTests)
--
Traceback (most recent call last):
  File 
"/Library/Python/2.7/site-packages/django/contrib/auth/tests/context_processors.py",
line 58, in test_message_attrs
self.assertContains(response, "Message 1")
  File "/Library/Python/2.7/site-packages/django/test/testcases.py",
line 637, in assertContains
msg_prefix + "Couldn't find '%s' in response" % text)
AssertionError: Couldn't find 'Message 1' in response

--
Ran 350 tests in 2354.881s

FAILED (failures=1, errors=1, skipped=1)
Destroying test database for alias 'default'...

But it never ran my tests.

Questions:

-What are the lines with the dots and F, S, and s?
-What are the 350 tests it ran?
-Why didn't it run my test?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Error with unit testing with Raven.

2012-12-14 Thread xina towner
I've found the solution. The problem was that I was using the
'raven.contrib.django.middleware.Sentry404CatchMiddleware' so the
Middleware was getting the 404 signals. I think that because of that the
test were not receiving the signals so when in the test we were checking
for 404 codes the tests were failing.

Thanks,

Ruben.

On 13 December 2012 20:22, xina towner  wrote:

> Hi, I'm trying to use Raven in order to send messages to my CI server.
>
> I had some tests that pass but suddenly they are failing. Does anyone
> knows why is that?
>
> Output:
>
> ==
> ERROR: test_not_individual (quests.tests.views.TaskDoTest)
> --
> Traceback (most recent call last):
>   File "/var/lib/jenkins/jobs/Newin/workspace/quests/tests/views.py", line 
> 632, in test_not_individual
> resp=self.client.get(reverse('task_do', args=[self.qu_t.id]))
>   File 
> "/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/django/test/client.py",
>  line 439, in get
> response = super(Client, self).get(path, data=data, **extra)
>   File 
> "/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/django/test/client.py",
>  line 244, in get
> return self.request(**r)
>   File 
> "/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/django/core/handlers/base.py",
>  line 188, in get_response
> response = middleware_method(request, response)
>   File 
> "/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/raven/contrib/django/middleware/__init__.py",
>  line 29, in process_response
> 'id': client.get_ident(result),
>   File 
> "/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/raven/base.py",
>  line 222, in get_ident
> return '$'.join(result)
> TypeError
>
> --
>
> I checked in the link :
>
>
> http://raven.readthedocs.org/en/latest/config/django.html#error-handling-middleware
>
> But I don't think that's the reason.
>
> --
> Thanks,
>
> Rubén
>
>


-- 
Gràcies,

Rubén

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Error with unit testing with Raven.

2012-12-13 Thread xina towner
Hi, I'm trying to use Raven in order to send messages to my CI server.

I had some tests that pass but suddenly they are failing. Does anyone knows
why is that?

Output:

==
ERROR: test_not_individual (quests.tests.views.TaskDoTest)
--
Traceback (most recent call last):
  File "/var/lib/jenkins/jobs/Newin/workspace/quests/tests/views.py",
line 632, in test_not_individual
resp=self.client.get(reverse('task_do', args=[self.qu_t.id]))
  File 
"/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/django/test/client.py",
line 439, in get
response = super(Client, self).get(path, data=data, **extra)
  File 
"/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/django/test/client.py",
line 244, in get
return self.request(**r)
  File 
"/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/django/core/handlers/base.py",
line 188, in get_response
response = middleware_method(request, response)
  File 
"/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/raven/contrib/django/middleware/__init__.py",
line 29, in process_response
'id': client.get_ident(result),
  File 
"/var/lib/jenkins/jobs/Newin/workspace/.env/local/lib/python2.7/site-packages/raven/base.py",
line 222, in get_ident
return '$'.join(result)
TypeError

--

I checked in the link :

http://raven.readthedocs.org/en/latest/config/django.html#error-handling-middleware

But I don't think that's the reason.

-- 
Thanks,

Rubén

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Keep getting TemplateDoesNotExist when unit testing

2012-03-03 Thread Calvin Cheng

Hi Jonas,

I am having exactly the same problem in one of my projects and I am not 
sure why.  Did you manage to solve it in the end?

Would appreciate it if you could share with me your solution if you did.

Regards,
Calvin


On Saturday, December 24, 2011 10:51:27 PM UTC+8, jonas wrote:
>
> Hello,
>
> I'm fairly new to Unit Testing.
>
> As I'm trying to setup a simple unit test in one of my Projects,
> it keeps returning a TemplateDoesNotExist Exception.
>
> It looks like for some reason the unit test framework can't locate my 
> template directory I've correctly defined in settings.py
>
> Here's the traceback:
>
> ==
> ERROR: test_url (gig.tests.GigURLTest)
> --
> Traceback (most recent call last):
>   File "/home/jonasg/dev/wiespeeltwaar/gig/tests.py", line 14, in test_url
> response = c.get('/')
>   File 
> "/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/test/client.py",
>  
> line 445, in get
> response = super(Client, self).get(path, data=data, **extra)
>   File 
> "/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/test/client.py",
>  
> line 229, in get
> return self.request(**r)
>   File 
> "/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/core/handlers/base.py",
>  
> line 111, in get_response
> response = callback(request, *callback_args, **callback_kwargs)
>   File "/home/jonasg/dev/wiespeeltwaar/../wiespeeltwaar/gig/views.py", 
> line 74, in index
> http_res = render_to_response('gig/index.html', c , 
> context_instance=RequestContext(request))
>   File 
> "/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/shortcuts/__init__.py",
>  
> line 20, in render_to_response
> return HttpResponse(loader.render_to_string(*args, **kwargs), 
> **httpresponse_kwargs)
>   File 
> "/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
>  
> line 181, in render_to_string
> t = get_template(template_name)
>   File 
> "/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
>  
> line 157, in get_template
> template, origin = find_template(template_name)
>   File 
> "/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
>  
> line 138, in find_template
> raise TemplateDoesNotExist(name)
> TemplateDoesNotExist: gig/index.html
>
>
> The unit test itself is simple:
>
> from django.test import TestCase
> from django.test.client import Client
>
> class GigURLTest(TestCase):
> def test_url(self):
> c = Client()
> response = c.get('/')
> self.assertEqual(response.status_code, 200)   
> 
>  
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/kvcalsd1X_UJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Keep getting TemplateDoesNotExist when unit testing

2011-12-24 Thread Jonas Geiregat
Hello,

I'm fairly new to Unit Testing.

As I'm trying to setup a simple unit test in one of my Projects,
it keeps returning a TemplateDoesNotExist Exception.

It looks like for some reason the unit test framework can't locate my template 
directory I've correctly defined in settings.py

Here's the traceback:

==
ERROR: test_url (gig.tests.GigURLTest)
--
Traceback (most recent call last):
  File "/home/jonasg/dev/wiespeeltwaar/gig/tests.py", line 14, in test_url
response = c.get('/')
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/test/client.py",
 line 445, in get
response = super(Client, self).get(path, data=data, **extra)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/test/client.py",
 line 229, in get
return self.request(**r)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/core/handlers/base.py",
 line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
  File "/home/jonasg/dev/wiespeeltwaar/../wiespeeltwaar/gig/views.py", line 74, 
in index
http_res = render_to_response('gig/index.html', c , 
context_instance=RequestContext(request))
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/shortcuts/__init__.py",
 line 20, in render_to_response
return HttpResponse(loader.render_to_string(*args, **kwargs), 
**httpresponse_kwargs)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
 line 181, in render_to_string
t = get_template(template_name)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
 line 157, in get_template
template, origin = find_template(template_name)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
 line 138, in find_template
raise TemplateDoesNotExist(name)
TemplateDoesNotExist: gig/index.html


The unit test itself is simple:

from django.test import TestCase
from django.test.client import Client

class GigURLTest(TestCase):
def test_url(self):
c = Client()
response = c.get('/')
self.assertEqual(response.status_code, 200) 

   

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Keep getting TemplateDoesNotExist when unit testing

2011-12-24 Thread Jonas Geiregat
Hello,

I'm fairly new to Unit Testing.

As I'm trying to setup a simple unit test in one of my Projects,
it keeps returning a TemplateDoesNotExist Exception.

It looks like for some reason the unit test framework can't locate my template 
directory I've correctly defined in settings.py

Here's the traceback:

==
ERROR: test_url (gig.tests.GigURLTest)
--
Traceback (most recent call last):
  File "/home/jonasg/dev/wiespeeltwaar/gig/tests.py", line 14, in test_url
response = c.get('/')
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/test/client.py",
 line 445, in get
response = super(Client, self).get(path, data=data, **extra)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/test/client.py",
 line 229, in get
return self.request(**r)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/core/handlers/base.py",
 line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
  File "/home/jonasg/dev/wiespeeltwaar/../wiespeeltwaar/gig/views.py", line 74, 
in index
http_res = render_to_response('gig/index.html', c , 
context_instance=RequestContext(request))
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/shortcuts/__init__.py",
 line 20, in render_to_response
return HttpResponse(loader.render_to_string(*args, **kwargs), 
**httpresponse_kwargs)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
 line 181, in render_to_string
t = get_template(template_name)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
 line 157, in get_template
template, origin = find_template(template_name)
  File 
"/home/jonasg/.virtualenvs/wiespeeltwaar/lib/python2.6/site-packages/django/template/loader.py",
 line 138, in find_template
raise TemplateDoesNotExist(name)
TemplateDoesNotExist: gig/index.html


The unit test itself is simple:

from django.test import TestCase
from django.test.client import Client

class GigURLTest(TestCase):
def test_url(self):
c = Client()
response = c.get('/')
self.assertEqual(response.status_code, 200) 

   

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Import error when unit testing with django.test.client on django 1.1.1

2011-11-24 Thread Erlendur Hákonarson
Thanks Xavier
I will research this better
but the path for the settings file is wrong in this error, it should be 
'bo.settings' not 'DER.settings'
but that might be because the tests do not have my project in their path

Thanks again
Erlendur

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/sYOZNTnBLCIJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Import error when unit testing with django.test.client on django 1.1.1

2011-11-23 Thread xordoquy
Hi

The error is:

> ImportError: Could not import settings 'DER.settings' (Is it on
> sys.path? Does it have syntax errors?): No module named DER.settings
> ERROR: Module: Test could not be imported (file:
> C:TFSSrc_BranchDER_UnitTestingboteststestListsTest.py).

You should google a bit on how to setup django tests with eclipse.
It looks like eclipse tests do not have your project in their paths
thus it doesn't find DER.settings.

Regards,
Xavier.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Import error when unit testing with django.test.client on django 1.1.1

2011-11-23 Thread Erlendur Hákonarson
I am trying to set up unit tests on my project
but when I try to import anything from f.e. django.test
then I get this error:
Traceback (most recent call last):
  File 
"C:\eclipse\plugins\org.python.pydev.debug_2.2.2.2011082312\pysrc\pydev_runfiles.py",
 
line 307, in __get_module_from_str
mod = __import__(modname)
  File "C:/TFSSrc_Branch/DER_UnitTesting/bo/tests/testLists\Test.py", line 
8, in 
from django.test.Client import Client
  File "C:\TFSSrc_Branch\DER_UnitTesting\django\test\__init__.py", line 6, 
in 
from django.test.testcases import TestCase
  File "C:\TFSSrc_Branch\DER_UnitTesting\django\test\testcases.py", line 
10, in 
from django.db import transaction
  File "C:\TFSSrc_Branch\DER_UnitTesting\django\db\__init__.py", line 9, in 

if not settings.DATABASE_ENGINE:
  File "C:\TFSSrc_Branch\DER_UnitTesting\django\conf\__init__.py", line 28, 
in __getattr__
self._import_settings()
  File "C:\TFSSrc_Branch\DER_UnitTesting\django\conf\__init__.py", line 59, 
in _import_settings
self._target = Settings(settings_module)
  File "C:\TFSSrc_Branch\DER_UnitTesting\django\conf\__init__.py", line 94, 
in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? 
Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'DER.settings' (Is it on sys.path? 
Does it have syntax errors?): No module named DER.settings
ERROR: Module: Test could not be imported (file: 
C:\TFSSrc_Branch\DER_UnitTesting\bo\tests\testLists\Test.py).

Here is my code:
import unittest
#from django.utils import unittest
from django.test.Client import Client

class TestLists(unittest.TestCase):

def setUp(self):
from django.test import Client
self.client =  Client()
self.client.login(username='erlendurh', password='e12345')

def tearDown(self):
pass

def testGetList(self):

self.client.get('/clearing/rep/contracts/from/2011-11-16/to/2011-11-26/')

if __name__ == "__main__":
unittest.main()

I would be very glad if someone could help me with this problem :)

Best regards
Erlendur

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/Uqka7hRGThwJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-22 Thread Nan

> Use Mock and assert_called_with:
> http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.assert_ca...
> In this case you'd set theAPI.call as your mock and check that under 
> different conditions it is called correctly.

Oh, perfect -- thank you, that will help a lot!

> You don't need mocks or dependency injection in this case. Just separate the
> message construction code, so you can test it in isolation:

Yeah, it looks like that may be a next step, but I'm hesitant to do
even that much refactoring without tests already in place, due to the
complexity and fragility of the logic.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-21 Thread Andrew Brookins
You don't need mocks or dependency injection in this case. Just separate the 
message construction code, so you can test it in isolation:

# myapp.views
from django.http import HttpResponse
from myapp.models import CurrentState
from myapp.exceptions import ApiFailureException
from third_party.api import theAPI 


def my_view(request):
state = CurrentState.get(pk=request. session.get('state'))
new_data = request.POST.get('new_data')
state.update(new_data)
msg = _get_message(state, new_data)
result = theAPI.call(msg)
if result is None:
return ApiFailureException()
return HttpResponse('success')

def _get_message(state, new_data):
message = None
if state.x() and state.y():
message = '%s/%s' % (state.a(), new_data)
elif state.z():
message = '%s/%s' % (state.b(), new_data)
else:
message = state.c()
return message


# third_party.api
import urllib, urllib2
from django.conf import settings

class theAPI(object):
def call(self, msg=''):
data = urllib.urlencode({'message': msg})
req = urllib2.Request(url=settings.THIRD_PARTY_API_URL, data=data)
resp = urllib2.urlopen(req)
return resp.status == '200' 


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/sx939cizEBYJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-21 Thread Andy McKay

On 2011-06-20, at 12:52 PM, Nan wrote:

> I'm not testing the third-party service.  I need to test *what I send
> to them*. 

Use Mock and assert_called_with:

http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.assert_called_with

In this case you'd set theAPI.call as your mock and check that under different 
conditions it is called correctly.
--
  Andy McKay
  a...@clearwind.ca
  twitter: @andymckay
 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-21 Thread Nan


> That's what I was suggesting; that way the view becomes simple enough that
> anyone looking at it can be assured of its correctness, without a host of
> unit tests. Those tests can be applied to the functions that actually
> construct the messages.

Right, it's really those supporting functions that I need to test, but
they currently don't return anything more informative than the view
does (i.e. blank HttpResponse)

> If this is all for a refactoring, then you're probably on the right track
> there -- instrument the existing object for testing, rather than
> restructuring the view first. Get the code into a state where you can trust
> it, and then you can start restructuring it to make it more easily testable
> in the future.

Well, it's not just for refactoring -- we're planning to add
additional features that will make the state logic even more complex.
But if more testable code would require refactoring, I'd like to
already have some form of tests in place anyway because there's a
decent chance that refactoring without them would break something.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-21 Thread Ian Clelland
On Tue, Jun 21, 2011 at 7:30 AM, Nan <ringe...@gmail.com> wrote:

>
>
> > Your view function may indeed be too complex to test properly, and it
> sounds
> > like it is too tightly coupled with with the API call -- there is no way
> to
> > call the view without having it call the actual 3rd-party API as imported
> at
> > the top of the file.
>
> I'd be a little confused as to how to factor that out.  I mean, in the
> actual app that call is refactored behind a function that wraps the
> third-party API, and I could theoretically monkey-patch something over
> that function call for unit testing.  But the view still has to return
> an HttpResponse, and a blank one.
>

You're right, the view does need to return an HttpResponse; there's nothing
you can do about that. My point about tight coupling was that your view has
also been made responsible for instantiating the API wrapper that it thinks
it needs, and there's no way to tell it not to. In other frameworks, I would
immediately suggest using dependency injection -- the view depends on an API
wrapper instance, so it shouldn't be creating that instance; that should be
provided to it:

def my_view(request, api):
...
result = api.call(msg)

because then you could call my_view(request, theAPI()) in most
circumstances, but my_view(request, fake_api) in test code. Unfortunately,
the view is almost always called directly by Django, and you don't have much
control over its parameters.


> > The other way is to make your view function as simple as possible --
> simple
> > enough that it is obviously correct, without any unit tests. Take
> > *everything* that can affect the message which is passed to the API, and
> > abstract that into another function that the view can call. Then test
> *that*
> > function as a unit.
>
> Yes, it is very complex: it has to assess about 30 different potential
> states via nested conditionals.  It's actually broken down into a
> number of sub-functions that each deal with a few sub-states; and
> while refactoring might be a good idea, I wouldn't want to even
> attempt that before having some good unit tests in place!
>
> I think what you're suggesting (correct me if I'm wrong) is to have
> the top-level view function be the only place the API is called, and
> to use only a single call; every other sub-function that reaches an
> exit state should instead return a string containing the message to
> send?
>

That's what I was suggesting; that way the view becomes simple enough that
anyone looking at it can be assured of its correctness, without a host of
unit tests. Those tests can be applied to the functions that actually
construct the messages. But, see below -- I didn't realise that this effort
was to aid in refactoring the code.


>
> Thinking aloud, my concern then becomes that some of the sub-functions
> must actually make multiple API calls.  So we'd have to be returning
> tuples or something instead.
>
> > If theAPI is a class, then give it methods like setTestMode() and
> > resetTestMode(), and use them in your setUp and tearDown methods. Then,
> if
> > test mode is enabled, don't actually make the third party call, just
> store
> > the passed-in message in a module-level or class-level list and return
> > success. After your view returns, check the list to see that the message
> was
> > correct.
>
> Oh!  Thank you!  I didn't understand before how a mock API might make
> that possible -- it makes a lot more sense now.  That soudns like the
> perfect way to do it.
>
> At least until we've got enough tests to make sure the refactoring is
> correct, I need to be able to create the tests without touching the
> actual view logic, so testing what the API receives makes the most
> sense to me.
>

If this is all for a refactoring, then you're probably on the right track
there -- instrument the existing object for testing, rather than
restructuring the view first. Get the code into a state where you can trust
it, and then you can start restructuring it to make it more easily testable
in the future.

Good luck! :)


-- 
Regards,
Ian Clelland
<clell...@gmail.com>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-21 Thread Nan


> Your view function may indeed be too complex to test properly, and it sounds
> like it is too tightly coupled with with the API call -- there is no way to
> call the view without having it call the actual 3rd-party API as imported at
> the top of the file.

I'd be a little confused as to how to factor that out.  I mean, in the
actual app that call is refactored behind a function that wraps the
third-party API, and I could theoretically monkey-patch something over
that function call for unit testing.  But the view still has to return
an HttpResponse, and a blank one.

> The other way is to make your view function as simple as possible -- simple
> enough that it is obviously correct, without any unit tests. Take
> *everything* that can affect the message which is passed to the API, and
> abstract that into another function that the view can call. Then test *that*
> function as a unit.

Yes, it is very complex: it has to assess about 30 different potential
states via nested conditionals.  It's actually broken down into a
number of sub-functions that each deal with a few sub-states; and
while refactoring might be a good idea, I wouldn't want to even
attempt that before having some good unit tests in place!

I think what you're suggesting (correct me if I'm wrong) is to have
the top-level view function be the only place the API is called, and
to use only a single call; every other sub-function that reaches an
exit state should instead return a string containing the message to
send?

Thinking aloud, my concern then becomes that some of the sub-functions
must actually make multiple API calls.  So we'd have to be returning
tuples or something instead.

> If theAPI is a class, then give it methods like setTestMode() and
> resetTestMode(), and use them in your setUp and tearDown methods. Then, if
> test mode is enabled, don't actually make the third party call, just store
> the passed-in message in a module-level or class-level list and return
> success. After your view returns, check the list to see that the message was
> correct.

Oh!  Thank you!  I didn't understand before how a mock API might make
that possible -- it makes a lot more sense now.  That soudns like the
perfect way to do it.

At least until we've got enough tests to make sure the refactoring is
correct, I need to be able to create the tests without touching the
actual view logic, so testing what the API receives makes the most
sense to me.


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-20 Thread Ian Clelland
On Mon, Jun 20, 2011 at 4:25 PM, Nan <ringe...@gmail.com> wrote:

>
> Hm, I'm not worried about receiving a valid response from the third-
> party API, just about testing the value of the "msg" parameter that's
> passed into it.  I need to test the msg parameter because it is in
> turn essentially a proxy for which state was reached in my_view.
>
> my_view is actually a great deal more complex than in the example, and
> is indeed broken into many smaller function calls.  I need to unit
> test to make sure that the logic is correct -- and since all those
> function calls return empty HttpResponse objects, I can't use their
> return values to test the correctness of their logic.
>

Your view function may indeed be too complex to test properly, and it sounds
like it is too tightly coupled with with the API call -- there is no way to
call the view without having it call the actual 3rd-party API as imported at
the top of the file.

There are a couple of ways out of this -- one is to use mocks, as suggested
before. Coupled with the dependency injection pattern, you would normally do
something to have the testing framework pass the mock API to the view, and
then you would query the mock at the end of the test to see what was passed
to it. Since Django's test framework is based around end-to-end testing
(making requests through TestCase.client and examining the response
returned,) this can be difficult to achieve.

The other way is to make your view function as simple as possible -- simple
enough that it is obviously correct, without any unit tests. Take
*everything* that can affect the message which is passed to the API, and
abstract that into another function that the view can call. Then test *that*
function as a unit.


>
> Just brainstorming here, could there be a way around this by placing a
> logging call of some sort in theAPI.call() that would only be executed
> during unit testing, and then to test the contents of the log?
>

This sounds like turning your API wrapper into a mock object at test time --
it might be the easiest way to do it, if you go the mock route.

If theAPI is a class, then give it methods like setTestMode() and
resetTestMode(), and use them in your setUp and tearDown methods. Then, if
test mode is enabled, don't actually make the third party call, just store
the passed-in message in a module-level or class-level list and return
success. After your view returns, check the list to see that the message was
correct.

Depending on the tests you have, you may want to have a way to tell the API
to return success or various kinds of failure. Most mocking frameworks have
ways of telling the mock objects what to return before making the method
calls.

At some point, though, I would start to become wary of putting too much
testing code in the real classes. (I'm sure there's an unpleasant name for
that kind of pattern)


>
>
> On Jun 20, 6:20 pm, DrBloodmoney <drbloodmo...@gmail.com> wrote:
> > On Mon, Jun 20, 2011 at 3:52 PM, Nan <ringe...@gmail.com> wrote:
> > > I'm not testing the third-party service.  I need to test *what I send
> > > to them*.  I.e. that the output of my_view is correct.  The trouble is
> > > that neither my_view nor the API call actually returns the output that
> > > I need to check.
> >
> > > Does that make sense?
> >
> > Mock is one good solution. Here's what I've done in the past
> > (basically half-assed mock):
> >
> > 1. Have representative data sets that are good for the service (eg.
> > whatever you send to them, and whatever they send you in return).
> > 2. Monkey patch the call:
> >
> > def hackety_patch():
> > from StringIO import StringIO
> > data = StringIO(testdata_response_from_API)
> > data.seek(0)
> > return data.read()
> >
> > # in TestCase subclass
> > def setUp(self):
> > third_party.api.urllib2.urlopen = hackety_patch
> >
> > def tearDown(self):
> > third_party.api.urllib2.urlopen = urllib2.urlopen
> >
> > 3. Break up your API calling code into more testable units to truly
> > isolate your independent code from the API calling code. It'll be much
> > easier to catch problems in the API integration code.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Regards,
Ian Clelland
<clell...@gmail.com>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-20 Thread Nan

Hm, I'm not worried about receiving a valid response from the third-
party API, just about testing the value of the "msg" parameter that's
passed into it.  I need to test the msg parameter because it is in
turn essentially a proxy for which state was reached in my_view.

my_view is actually a great deal more complex than in the example, and
is indeed broken into many smaller function calls.  I need to unit
test to make sure that the logic is correct -- and since all those
function calls return empty HttpResponse objects, I can't use their
return values to test the correctness of their logic.

Just brainstorming here, could there be a way around this by placing a
logging call of some sort in theAPI.call() that would only be executed
during unit testing, and then to test the contents of the log?


On Jun 20, 6:20 pm, DrBloodmoney <drbloodmo...@gmail.com> wrote:
> On Mon, Jun 20, 2011 at 3:52 PM, Nan <ringe...@gmail.com> wrote:
> > I'm not testing the third-party service.  I need to test *what I send
> > to them*.  I.e. that the output of my_view is correct.  The trouble is
> > that neither my_view nor the API call actually returns the output that
> > I need to check.
>
> > Does that make sense?
>
> Mock is one good solution. Here's what I've done in the past
> (basically half-assed mock):
>
> 1. Have representative data sets that are good for the service (eg.
> whatever you send to them, and whatever they send you in return).
> 2. Monkey patch the call:
>
> def hackety_patch():
>     from StringIO import StringIO
>     data = StringIO(testdata_response_from_API)
>     data.seek(0)
>     return data.read()
>
> # in TestCase subclass
> def setUp(self):
>     third_party.api.urllib2.urlopen = hackety_patch
>
> def tearDown(self):
>     third_party.api.urllib2.urlopen = urllib2.urlopen
>
> 3. Break up your API calling code into more testable units to truly
> isolate your independent code from the API calling code. It'll be much
> easier to catch problems in the API integration code.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-20 Thread DrBloodmoney
On Mon, Jun 20, 2011 at 3:52 PM, Nan  wrote:
> I'm not testing the third-party service.  I need to test *what I send
> to them*.  I.e. that the output of my_view is correct.  The trouble is
> that neither my_view nor the API call actually returns the output that
> I need to check.
>
> Does that make sense?

Mock is one good solution. Here's what I've done in the past
(basically half-assed mock):

1. Have representative data sets that are good for the service (eg.
whatever you send to them, and whatever they send you in return).
2. Monkey patch the call:

def hackety_patch():
from StringIO import StringIO
data = StringIO(testdata_response_from_API)
data.seek(0)
return data.read()

# in TestCase subclass
def setUp(self):
third_party.api.urllib2.urlopen = hackety_patch

def tearDown(self):
third_party.api.urllib2.urlopen = urllib2.urlopen

3. Break up your API calling code into more testable units to truly
isolate your independent code from the API calling code. It'll be much
easier to catch problems in the API integration code.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-20 Thread Nan
I'm not testing the third-party service.  I need to test *what I send
to them*.  I.e. that the output of my_view is correct.  The trouble is
that neither my_view nor the API call actually returns the output that
I need to check.

Does that make sense?



On Jun 20, 1:59 pm, Daniel Roseman  wrote:
> On Monday, June 20, 2011 6:07:59 PM UTC+1, Nan wrote:
>
> > In most situations, my app, upon receiving an HTTP request, sends data
> > to a third-party API, and returns an empty HttpResponse.  I need to
> > test that the correct data is sent to the third-party API based on
> > internal application state.  I'm perplexed as to how to intercept this
> > data in a unit test.
>
> > Here's a sort of dummy version of the code in question.  What I need
> > to be able to test is that depending on the data in the CurrentState
> > object, the value of the "message" parameter sent by the API call is
> > correct.  Any suggestions?
>
> Don't test the third-party service. You don't have any control over it - you
> just have to assume that it works, and always does what it says in the
> published API.
>
> The only bit you need to test is your interaction with that API. The best
> way to do that is to use a technique called "mocking", where you replace the
> part of your code which calls the API with a dummy object which always
> returns what you tell it. Of course, there are plenty of libraries to enable
> this, but my favourite is Michael Foord's one, simply called "mock" -
> seehttp://www.voidspace.org.uk/python/mock/
>
> Using mock, you would patch your "theAPI" class to use a mock function in
> place of the "call" method, which returns the right data depending on the
> parameters. Then assert that your code does the correct things in response.
> --
> DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit-Testing Dilemma

2011-06-20 Thread Daniel Roseman
On Monday, June 20, 2011 6:07:59 PM UTC+1, Nan wrote:
>
> In most situations, my app, upon receiving an HTTP request, sends data 
> to a third-party API, and returns an empty HttpResponse.  I need to 
> test that the correct data is sent to the third-party API based on 
> internal application state.  I'm perplexed as to how to intercept this 
> data in a unit test. 
>
> Here's a sort of dummy version of the code in question.  What I need 
> to be able to test is that depending on the data in the CurrentState 
> object, the value of the "message" parameter sent by the API call is 
> correct.  Any suggestions? 
>
 
Don't test the third-party service. You don't have any control over it - you 
just have to assume that it works, and always does what it says in the 
published API.

The only bit you need to test is your interaction with that API. The best 
way to do that is to use a technique called "mocking", where you replace the 
part of your code which calls the API with a dummy object which always 
returns what you tell it. Of course, there are plenty of libraries to enable 
this, but my favourite is Michael Foord's one, simply called "mock" - 
see http://www.voidspace.org.uk/python/mock/

Using mock, you would patch your "theAPI" class to use a mock function in 
place of the "call" method, which returns the right data depending on the 
parameters. Then assert that your code does the correct things in response.
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/Xd_8Uy6-X2QJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Unit-Testing Dilemma

2011-06-20 Thread Nan
In most situations, my app, upon receiving an HTTP request, sends data
to a third-party API, and returns an empty HttpResponse.  I need to
test that the correct data is sent to the third-party API based on
internal application state.  I'm perplexed as to how to intercept this
data in a unit test.

Here's a sort of dummy version of the code in question.  What I need
to be able to test is that depending on the data in the CurrentState
object, the value of the "message" parameter sent by the API call is
correct.  Any suggestions?

# myapp.views
from myapp.models import CurrentState
from myapp.exceptions import *
from third_party.api import theAPI

def my_view(request):
state = CurrentState.get(pk=request.session.get('state'))
new_data = request.POST.get('new_data')
state.update(new_data)
if state.x() and state.y():
result = theAPI.call(msg='%s/%s' % (state.a(), new_data))
elif state.z():
result = theAPI.call(msg='%s/%s' % (state.b(), new_data))
else:
result = theAPI.call(msg=state.c())
if not result:
raise ApiFailureException()
return HttpResponse('success')


# third_party.api
import urllib, urllib2
from django.conf import settings

class theAPI(object):
def call(self, msg=''):
data = urllib.urlencode({'message': msg})
req = urllib2.Request(url=settings.THIRD_PARTY_API_URL, 
data=data)
resp = urllib2.urlopen(req)
return resp.status == '200'

Thanks, folks

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: unit testing and file location

2011-05-11 Thread Calvin Spealman
You can run your tests with their own --settings parameter with the specific
variations you want to test under.

On May 10, 2011 5:21 PM, "Brian Craft"  wrote:

I would like unit tests that do file manipulations to run with a
different storage "location", so they're not manipulating real app
files. Is there a good way to do this? Is there a way to override
model field initializers, so I can instance a model, passing in the
'storage' parameter for an ImageField in the model?

--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



unit testing and file location

2011-05-10 Thread Brian Craft
I would like unit tests that do file manipulations to run with a
different storage "location", so they're not manipulating real app
files. Is there a good way to do this? Is there a way to override
model field initializers, so I can instance a model, passing in the
'storage' parameter for an ImageField in the model?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit Testing: temporarily altering django settings

2011-02-21 Thread Phlip
On Feb 21, 12:47 pm, Cody Django  wrote:

> Thanks -- I didn't know about mock objects, and this is good to know.
> But this doesn't feel like this is the solution I'm looking for.  It's
> a large project, and your proposal would require extensive patching.

Does your project access the CAPTCHA settings in many different
places??

Either way, I think you still don't grok mocks.

But try Mikhail's suggestion first - just reach into the settings and
change them, before the call to client.get().

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit Testing: temporarily altering django settings

2011-02-21 Thread Mikhail Korobov
Why doesn't setattr work? Just make sure you're setting the proper
option because apps often cache options at e.g. their 'config.py' file
in order to provide default values:

# captha_app/config.py
from django.conf import settings
CAPTCHA = getattr(settings, 'CAPTCHA', True)

So you'll have to change captcha_app.config.CAPTCHA, not the
settings.CAPTCHA in this case.

On 22 фев, 01:47, Cody Django  wrote:
> Thanks -- I didn't know about mock objects, and this is good to know.
> But this doesn't feel like this is the solution I'm looking for.  It's
> a large project, and your proposal would require extensive patching.
>
> Is the solution to create a new testrunner that sets a different
> environment (with different settings) for each app?  Is there another
> way to fool a testcase into thinking that an app has not been
> installed?
>
> Thanks again,
>
> Cody
>
> On Feb 17, 2:00 pm, Phlip  wrote:
>
>
>
>
>
>
>
> > On Feb 17, 12:03 pm, Cody Django  wrote:
>
> > > For example, I have a captcha that is used in parts of a site that
> > > affects form logic.
> > > The django settings has a variable CAPTCHA = True, which acts as a
> > > switch.
>
> > > I'd like to change this setting in the setup for each TestCase.
>
> > You should use a mock object, to fake a-priori things like stochastic
> > user input.
>
> > Python's mock library has a 'patch.object' feature which mocks a
> > method on a class, even before objects of that class are instantiated.
>
> > In most of your setUp calls, patch the captcha handler to trivially
> > pass it, without real user input.
>
> > To test the captcha, mock it to pass or fail.
>
> > --
> >   Phlip
> >  http://c2.com/cgi/wiki?ZeekLand

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit Testing: temporarily altering django settings

2011-02-21 Thread Cody Django
Thanks -- I didn't know about mock objects, and this is good to know.
But this doesn't feel like this is the solution I'm looking for.  It's
a large project, and your proposal would require extensive patching.

Is the solution to create a new testrunner that sets a different
environment (with different settings) for each app?  Is there another
way to fool a testcase into thinking that an app has not been
installed?

Thanks again,

Cody



On Feb 17, 2:00 pm, Phlip  wrote:
> On Feb 17, 12:03 pm, Cody Django  wrote:
>
> > For example, I have a captcha that is used in parts of a site that
> > affects form logic.
> > The django settings has a variable CAPTCHA = True, which acts as a
> > switch.
>
> > I'd like to change this setting in the setup for each TestCase.
>
> You should use a mock object, to fake a-priori things like stochastic
> user input.
>
> Python's mock library has a 'patch.object' feature which mocks a
> method on a class, even before objects of that class are instantiated.
>
> In most of your setUp calls, patch the captcha handler to trivially
> pass it, without real user input.
>
> To test the captcha, mock it to pass or fail.
>
> --
>   Phlip
>  http://c2.com/cgi/wiki?ZeekLand

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit Testing: temporarily altering django settings

2011-02-17 Thread Phlip
On Feb 17, 12:03 pm, Cody Django  wrote:

> For example, I have a captcha that is used in parts of a site that
> affects form logic.
> The django settings has a variable CAPTCHA = True, which acts as a
> switch.
>
> I'd like to change this setting in the setup for each TestCase.

You should use a mock object, to fake a-priori things like stochastic
user input.

Python's mock library has a 'patch.object' feature which mocks a
method on a class, even before objects of that class are instantiated.

In most of your setUp calls, patch the captcha handler to trivially
pass it, without real user input.

To test the captcha, mock it to pass or fail.

--
  Phlip
  http://c2.com/cgi/wiki?ZeekLand

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Unit Testing: temporarily altering django settings

2011-02-17 Thread Cody Django
For example, I have a captcha that is used in parts of a site that
affects form logic.
The django settings has a variable CAPTCHA = True, which acts as a
switch.

I'd like to change this setting in the setup for each TestCase.  The
regular unittests tests (in which we are assuming the captcha is off)
will not be affected, since their testcase has ensured that the
CAPTCHA setting is set to False.  The captcha app unittests will be
able to test the new form logic, since their testcase has set the
CAPTCHA setting to True.

I thought I'd be able to simply use a setattr, but apparently it's not
so easy.

Is the only solution to create a new testrunner that actually sets up
a different environment (with different settings) for each app?

Thanks,

Cody

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit testing in django without using test client

2010-09-17 Thread Paul Winkler
On Fri, Sep 17, 2010 at 10:58:19AM +0530, girish shabadimath wrote:
> hi Paul,
> 
> thanks for d reply,,,but im new to python n django,,,dint do ne python unit
> testing before,,can u plz give me some links or hints to start with...

http://docs.djangoproject.com/en/1.2/topics/testing/ 
has plenty of examples, many without using django.test.client.

-- 

Paul Winkler
http://www.slinkp.com

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit testing in django without using test client

2010-09-17 Thread Paul Winkler
On Fri, Sep 17, 2010 at 10:58:19AM +0530, girish shabadimath wrote:
> hi Paul,
> 
> thanks for d reply,,,but im new to python n django,,,dint do ne python unit
> testing before,,can u plz give me some links or hints to start with...

http://docs.djangoproject.com/en/1.2/topics/testing/ 
has plenty of examples, many without using django.test.client.

-- 

Paul Winkler
http://www.slinkp.com

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit testing in django without using test client

2010-09-17 Thread Carlton Gibson
Hi Girish,

On 17 Sep 2010, at 06:28, girish shabadimath wrote:

> thanks for d reply,,,but im new to python n django,,,dint do ne python unit 
> testing before,,can u plz give me some links or hints to start with...


IN that case I'd recommend this book: 

http://www.amazon.com/Django-Testing-Debugging-Karen-Tracey/dp/1847197566/

It's very good. It says 1.1 in the title but it'll be good for any 1.x at 
least. 

If you don't want the paper version, I know Packt do ebooks too.

Regards,
Carlton

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit testing in django without using test client

2010-09-16 Thread girish shabadimath
hi Paul,

thanks for d reply,,,but im new to python n django,,,dint do ne python unit
testing before,,can u plz give me some links or hints to start with...

On Thu, Sep 16, 2010 at 8:09 PM, Paul Winkler <sli...@gmail.com> wrote:

> On Sep 16, 10:11 am, girish shabadimath <girishmss.1...@gmail.com>
> wrote:
> > thanks for reply,
> > actually i used unit test to test urls and other view functions,,,there
> is a
> > module called Client() in django which acts as a browser to test urls,,,
> >
> > my problem is ,i want to test other methods in my project,,, how to do
> > so, without making use of django's test client..?..
>
> Exactly the same way you test any other python code. What's the
> problem?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@googlegroups.com>
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Girish M S

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: unit testing and not creating database for read only database

2010-09-16 Thread keith
created http://code.djangoproject.com/ticket/14296

On Sep 16, 4:22 pm, keith  wrote:
> I have the same problem, have you logged a ticket for this?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: unit testing and not creating database for read only database

2010-09-16 Thread keith
I have the same problem, have you logged a ticket for this?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit testing in django without using test client

2010-09-16 Thread Paul Winkler
On Sep 16, 10:11 am, girish shabadimath 
wrote:
> thanks for reply,
> actually i used unit test to test urls and other view functions,,,there is a
> module called Client() in django which acts as a browser to test urls,,,
>
> my problem is ,i want to test other methods in my project,,, how to do
> so, without making use of django's test client..?..

Exactly the same way you test any other python code. What's the
problem?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit testing in django without using test client

2010-09-16 Thread girish shabadimath
thanks for reply,
actually i used unit test to test urls and other view functions,,,there is a
module called Client() in django which acts as a browser to test urls,,,

my problem is ,i want to test other methods in my project,,, how to do
so, without making use of django's test client..?..


On Thu, Sep 16, 2010 at 7:27 PM, Shawn Milochik  wrote:

> You can use Python's unittest module to test any Python code (including
> Django code).
>
> What is it about Django's test client or TestCase class that is a problem
> for you?
>
> Shawn
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Girish M S

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit testing in django without using test client

2010-09-16 Thread Shawn Milochik
You can use Python's unittest module to test any Python code (including Django 
code).

What is it about Django's test client or TestCase class that is a problem for 
you?

Shawn

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Unit testing in django without using test client

2010-09-16 Thread girish shabadimath
hi,,,

i need to do unit testing in one of d django project, is there any other way
to test functions ( or methods ) without using test client..?

-- 
Girish M S

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django --Unit testing view functions

2010-09-06 Thread girish shabadimath
hi,,,
anybody help me with testing django views,,,

* wat all things need to be tested for view functions..?

* little bit confused about d usage of these two--
self.failUnlessEquals(XXX, XXX)  and
self.assertEquals(XXX, XXX) both seems to be same for me,,

* any related books or links is appreciated

Thanks in advance..!!


-- 
Girish M S

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: defining models for unit testing only

2010-08-22 Thread Atamert Ölçgen
Hi,

> I wrote a django 'app', thats basically just a class that takes a
> Queryset, some other information, and then outputs an HttpResponse
> object (it does some other things too). How do I write unit tests for
> this class? The app itself does not contain any models, yet the
> functionality of the class depends on a model. The testing docs do not
> mention anything about this.

If you define some models in your tests.py file they will be available (only) 
when you run your tests.


-- 
Saygılarımla,
Atamert Ölçgen

-+-
--+
+++

www.muhuk.com
mu...@jabber.org

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



defining models for unit testing only

2010-08-21 Thread mack the finger
I wrote a django 'app', thats basically just a class that takes a
Queryset, some other information, and then outputs an HttpResponse
object (it does some other things too). How do I write unit tests for
this class? The app itself does not contain any models, yet the
functionality of the class depends on a model. The testing docs do not
mention anything about this.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: unit testing and not creating database for read only database

2010-07-29 Thread thusjanthan
Any suggestions?

On Jul 7, 2:21 pm, thusjanthan  wrote:
> Hi,
>
> So I have a read only database called "information" which has been
> modeled in the django framework with the managed=false for the META on
> all its tables. When I run unit tests on another app I do not want the
> unit tests to go and create a test database for "information" but
> would rather like to use the information's table's values to compute
> some other tests for this app. Is there any way to do that in django?
>
> Thusjanthan.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



unit testing and not creating database for read only database

2010-07-07 Thread thusjanthan
Hi,

So I have a read only database called "information" which has been
modeled in the django framework with the managed=false for the META on
all its tables. When I run unit tests on another app I do not want the
unit tests to go and create a test database for "information" but
would rather like to use the information's table's values to compute
some other tests for this app. Is there any way to do that in django?

Thusjanthan.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Problem with queryset during model unit-testing

2010-02-12 Thread Alexey
First, the code of my tests.py

def test_get_current(self):
m = Member.objects.create(...)
q = Question.objects.create(name="q1", text="q1",
start_datetime=self.day_before, close_datetime=self.day_after,
type=self.type)
r = Response.objects.create(question=q, text='response')
expected = q, None
#self.assertEquals(expected, Question.objects.get_current(m.id))

q2 = Question.objects.create(name="q2", text="q2",
start_datetime=self.day_before, close_datetime=self.day_after,
type=self.type)
#self.assertEquals(expected, Question.objects.get_current(m.id))
MemberResponse.objects.create(member=m, response=r)
#expected = q2, None
#self.assertEquals(expected, Question.objects.get_current(m.id))
#doesn't work!
print
Question.objects.all().exclude(response__memberresponse__member=m)
print
Question.objects.all().exclude(response__memberresponse__member=m)

I've got unexpected results in my get_current function, so, I
commented it and tried to debug by printing main queryset used inside
function and got also strange results:

...
Installing index for ... model
[, ]
[]
.
--
Ran 5 tests in 3.125s

I'm wondering, why QuerySet with the same arguments returns first
wrong data, but by the next call - correct and how can I avoid it?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Unit testing Templatetags

2010-02-07 Thread Jari Pennanen
Hey!

Thanks a lot, that seems obvious now...

I found out that doing this:

template.libraries['django.templatetags.mytest'] = register

I can then use {% load mytest %} ... for the tags.

On 7 helmi, 22:19, Rolando Espinoza La Fuente <dark...@gmail.com>
wrote:
> You can see example code 
> here:http://github.com/darkrho/django-dummyimage/blob/master/dummyimage/te...
Great example.

IMO, there should be more unit-testing examples in Django
documentation, templatetags should be one...

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



  1   2   >