Re: testing newbie - help requested: app works, tests give errors

2023-05-10 Thread 'Bob Aalsma' via Django users
Hmm, when I remove the raise CommandError statement and replace it with 
self.stdout.write, everything works well.

This helps me to point further studies. Thx!
On Wednesday, May 10, 2023 at 2:33:18 PM UTC+2 Bob Aalsma wrote:

> Ah, yes, thanks.
>
> I hesitate to comment on "If I understood the error right." ;)
>
> Umm, my problem here is that I think I'm using the exact same *code* 
> "manually" without errors. 
> I think I'm also using the same *values* for the manual and test runs.
> So I don't understand the reason for the differences in output.
>
> On Wednesday, May 10, 2023 at 2:18:33 PM UTC+2 Vishesh Mangla wrote:
>
>> If I understood the error right.
>>
>> On Wed, May 10, 2023 at 5:47 PM Vishesh Mangla  
>> wrote:
>>
>>> Probably this would help: 
>>> https://stackoverflow.com/questions/8609192/what-is-the-difference-between-null-true-and-blank-true-in-django
>>>
>>> On Wed, May 10, 2023 at 5:45 PM 'Bob Aalsma' via Django users <
>>> django...@googlegroups.com> wrote:
>>>
 Sorry Vishesh, thanks for the quick answer but I have no idea what you 
 mean.

 On Wednesday, May 10, 2023 at 2:00:51 PM UTC+2 Vishesh Mangla wrote:

> False or True check for yourself.
>
> On Wed, 10 May, 2023, 17:29 Vishesh Mangla,  
> wrote:
>
>> It looks like you are passing a null but null=False is not set
>>
>> On Wed, 10 May, 2023, 17:27 'Bob Aalsma' via Django users, <
>> django...@googlegroups.com> wrote:
>>
>>> I'm trying to test a django-admin command and don't understand why 
>>> the tests give errors on the code while the code works as expected.
>>>
>>> I'm under the impression that the *raise CommandError* is ignored 
>>> by the test, but don't understand why this would be.
>>>
>>> Please help.
>>>
>>> Running the code shows:
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> populate_source 0
>>>
>>> *CommandError: Alleen hele getallen > 0 toegestaan*
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> populate_source 1
>>>
>>> *Teksten zijn gegenereerd voor tekstlengte 1*
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> populate_source 1
>>>
>>> *CommandError: Teksten voor nummer 1 zijn al eerder gegenereerd*
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> populate_source 7
>>>
>>> *CommandError: Opgegeven sleutel 7 niet gevonden*
>>>
>>> Running the tests shows
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> test tests.test_sources_app_command_populate
>>>
>>> Found 3 test(s).
>>>
>>> Creating test database for alias 'default'...
>>>
>>> System check identified no issues (0 silenced).
>>>
>>> EEE
>>>
>>>
>>> ==
>>>
>>> ERROR: test_command_output_been_there 
>>> (tests.test_sources_app_command_populate.PopulateSourceTests.test_command_output_been_there)
>>>
>>> Test for failure: in_use = True.
>>>
>>>
>>> --
>>>
>>> Traceback (most recent call last):
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
>>>  
>>> line 89, in _execute
>>>
>>> return self.cursor.execute(sql, params)
>>>
>>>
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py",
>>>  
>>> line 328, in execute
>>>
>>> return super().execute(query, params)
>>>
>>>^^
>>>
>>> sqlite3.IntegrityError: NOT NULL constraint failed: 
>>> domain_sources_app_characternumber.number_of_combinations
>>>
>>>
>>> The above exception was the direct cause of the following exception:
>>>
>>>
>>> Traceback (most recent call last):
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/tests/test_sources_app_command_populate.py",
>>>  
>>> line 30, in test_command_output_been_there
>>>
>>> thingy.save()
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>>  
>>> line 814, in save
>>>
>>> self.save_base(
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>>  
>>> line 877, in save_base
>>>
>>> updated = self._save_table(
>>>
>>>   ^
>>>
>>>   File 
>>> 

Re: testing newbie - help requested: app works, tests give errors

2023-05-10 Thread 'Bob Aalsma' via Django users
Ah, yes, thanks.

I hesitate to comment on "If I understood the error right." ;)

Umm, my problem here is that I think I'm using the exact same *code* 
"manually" without errors. 
I think I'm also using the same *values* for the manual and test runs.
So I don't understand the reason for the differences in output.

On Wednesday, May 10, 2023 at 2:18:33 PM UTC+2 Vishesh Mangla wrote:

> If I understood the error right.
>
> On Wed, May 10, 2023 at 5:47 PM Vishesh Mangla  
> wrote:
>
>> Probably this would help: 
>> https://stackoverflow.com/questions/8609192/what-is-the-difference-between-null-true-and-blank-true-in-django
>>
>> On Wed, May 10, 2023 at 5:45 PM 'Bob Aalsma' via Django users <
>> django...@googlegroups.com> wrote:
>>
>>> Sorry Vishesh, thanks for the quick answer but I have no idea what you 
>>> mean.
>>>
>>> On Wednesday, May 10, 2023 at 2:00:51 PM UTC+2 Vishesh Mangla wrote:
>>>
 False or True check for yourself.

 On Wed, 10 May, 2023, 17:29 Vishesh Mangla,  
 wrote:

> It looks like you are passing a null but null=False is not set
>
> On Wed, 10 May, 2023, 17:27 'Bob Aalsma' via Django users, <
> django...@googlegroups.com> wrote:
>
>> I'm trying to test a django-admin command and don't understand why 
>> the tests give errors on the code while the code works as expected.
>>
>> I'm under the impression that the *raise CommandError* is ignored by 
>> the test, but don't understand why this would be.
>>
>> Please help.
>>
>> Running the code shows:
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>> populate_source 0
>>
>> *CommandError: Alleen hele getallen > 0 toegestaan*
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>> populate_source 1
>>
>> *Teksten zijn gegenereerd voor tekstlengte 1*
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>> populate_source 1
>>
>> *CommandError: Teksten voor nummer 1 zijn al eerder gegenereerd*
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>> populate_source 7
>>
>> *CommandError: Opgegeven sleutel 7 niet gevonden*
>>
>> Running the tests shows
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>> test tests.test_sources_app_command_populate
>>
>> Found 3 test(s).
>>
>> Creating test database for alias 'default'...
>>
>> System check identified no issues (0 silenced).
>>
>> EEE
>>
>> ==
>>
>> ERROR: test_command_output_been_there 
>> (tests.test_sources_app_command_populate.PopulateSourceTests.test_command_output_been_there)
>>
>> Test for failure: in_use = True.
>>
>> --
>>
>> Traceback (most recent call last):
>>
>>   File 
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
>>  
>> line 89, in _execute
>>
>> return self.cursor.execute(sql, params)
>>
>>
>>
>>   File 
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py",
>>  
>> line 328, in execute
>>
>> return super().execute(query, params)
>>
>>^^
>>
>> sqlite3.IntegrityError: NOT NULL constraint failed: 
>> domain_sources_app_characternumber.number_of_combinations
>>
>>
>> The above exception was the direct cause of the following exception:
>>
>>
>> Traceback (most recent call last):
>>
>>   File 
>> "/Users/werker/Projects/domain_reader/tests/test_sources_app_command_populate.py",
>>  
>> line 30, in test_command_output_been_there
>>
>> thingy.save()
>>
>>   File 
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>  
>> line 814, in save
>>
>> self.save_base(
>>
>>   File 
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>  
>> line 877, in save_base
>>
>> updated = self._save_table(
>>
>>   ^
>>
>>   File 
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>  
>> line 1020, in _save_table
>>
>> results = self._do_insert(
>>
>>   
>>
>>   File 
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>  
>> line 1061, in _do_insert
>>
>> return 

Re: testing newbie - help requested: app works, tests give errors

2023-05-10 Thread Vishesh Mangla
If I understood the error right.

On Wed, May 10, 2023 at 5:47 PM Vishesh Mangla 
wrote:

> Probably this would help:
> https://stackoverflow.com/questions/8609192/what-is-the-difference-between-null-true-and-blank-true-in-django
>
> On Wed, May 10, 2023 at 5:45 PM 'Bob Aalsma' via Django users <
> django-users@googlegroups.com> wrote:
>
>> Sorry Vishesh, thanks for the quick answer but I have no idea what you
>> mean.
>>
>> On Wednesday, May 10, 2023 at 2:00:51 PM UTC+2 Vishesh Mangla wrote:
>>
>>> False or True check for yourself.
>>>
>>> On Wed, 10 May, 2023, 17:29 Vishesh Mangla, 
>>> wrote:
>>>
 It looks like you are passing a null but null=False is not set

 On Wed, 10 May, 2023, 17:27 'Bob Aalsma' via Django users, <
 django...@googlegroups.com> wrote:

> I'm trying to test a django-admin command and don't understand why the
> tests give errors on the code while the code works as expected.
>
> I'm under the impression that the *raise CommandError* is ignored by
> the test, but don't understand why this would be.
>
> Please help.
>
> Running the code shows:
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> populate_source 0
>
> *CommandError: Alleen hele getallen > 0 toegestaan*
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> populate_source 1
>
> *Teksten zijn gegenereerd voor tekstlengte 1*
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> populate_source 1
>
> *CommandError: Teksten voor nummer 1 zijn al eerder gegenereerd*
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> populate_source 7
>
> *CommandError: Opgegeven sleutel 7 niet gevonden*
>
> Running the tests shows
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> test tests.test_sources_app_command_populate
>
> Found 3 test(s).
>
> Creating test database for alias 'default'...
>
> System check identified no issues (0 silenced).
>
> EEE
>
> ==
>
> ERROR: test_command_output_been_there
> (tests.test_sources_app_command_populate.PopulateSourceTests.test_command_output_been_there)
>
> Test for failure: in_use = True.
>
> --
>
> Traceback (most recent call last):
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
> line 89, in _execute
>
> return self.cursor.execute(sql, params)
>
>
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py",
> line 328, in execute
>
> return super().execute(query, params)
>
>^^
>
> sqlite3.IntegrityError: NOT NULL constraint failed:
> domain_sources_app_characternumber.number_of_combinations
>
>
> The above exception was the direct cause of the following exception:
>
>
> Traceback (most recent call last):
>
>   File
> "/Users/werker/Projects/domain_reader/tests/test_sources_app_command_populate.py",
> line 30, in test_command_output_been_there
>
> thingy.save()
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
> line 814, in save
>
> self.save_base(
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
> line 877, in save_base
>
> updated = self._save_table(
>
>   ^
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
> line 1020, in _save_table
>
> results = self._do_insert(
>
>   
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
> line 1061, in _do_insert
>
> return manager._insert(
>
>
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/manager.py",
> line 87, in manager_method
>
> return getattr(self.get_queryset(), name)(*args, **kwargs)
>
>^^^
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/query.py",
> line 1805, in _insert
>
> return
> query.get_compiler(using=using).execute_sql(returning_fields)
>

Re: testing newbie - help requested: app works, tests give errors

2023-05-10 Thread Vishesh Mangla
Probably this would help:
https://stackoverflow.com/questions/8609192/what-is-the-difference-between-null-true-and-blank-true-in-django

On Wed, May 10, 2023 at 5:45 PM 'Bob Aalsma' via Django users <
django-users@googlegroups.com> wrote:

> Sorry Vishesh, thanks for the quick answer but I have no idea what you
> mean.
>
> On Wednesday, May 10, 2023 at 2:00:51 PM UTC+2 Vishesh Mangla wrote:
>
>> False or True check for yourself.
>>
>> On Wed, 10 May, 2023, 17:29 Vishesh Mangla,  wrote:
>>
>>> It looks like you are passing a null but null=False is not set
>>>
>>> On Wed, 10 May, 2023, 17:27 'Bob Aalsma' via Django users, <
>>> django...@googlegroups.com> wrote:
>>>
 I'm trying to test a django-admin command and don't understand why the
 tests give errors on the code while the code works as expected.

 I'm under the impression that the *raise CommandError* is ignored by
 the test, but don't understand why this would be.

 Please help.

 Running the code shows:

 (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
 populate_source 0

 *CommandError: Alleen hele getallen > 0 toegestaan*

 (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
 populate_source 1

 *Teksten zijn gegenereerd voor tekstlengte 1*

 (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
 populate_source 1

 *CommandError: Teksten voor nummer 1 zijn al eerder gegenereerd*

 (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
 populate_source 7

 *CommandError: Opgegeven sleutel 7 niet gevonden*

 Running the tests shows

 (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py test
 tests.test_sources_app_command_populate

 Found 3 test(s).

 Creating test database for alias 'default'...

 System check identified no issues (0 silenced).

 EEE

 ==

 ERROR: test_command_output_been_there
 (tests.test_sources_app_command_populate.PopulateSourceTests.test_command_output_been_there)

 Test for failure: in_use = True.

 --

 Traceback (most recent call last):

   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
 line 89, in _execute

 return self.cursor.execute(sql, params)



   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py",
 line 328, in execute

 return super().execute(query, params)

^^

 sqlite3.IntegrityError: NOT NULL constraint failed:
 domain_sources_app_characternumber.number_of_combinations


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


 Traceback (most recent call last):

   File
 "/Users/werker/Projects/domain_reader/tests/test_sources_app_command_populate.py",
 line 30, in test_command_output_been_there

 thingy.save()

   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
 line 814, in save

 self.save_base(

   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
 line 877, in save_base

 updated = self._save_table(

   ^

   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
 line 1020, in _save_table

 results = self._do_insert(

   

   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
 line 1061, in _do_insert

 return manager._insert(



   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/manager.py",
 line 87, in manager_method

 return getattr(self.get_queryset(), name)(*args, **kwargs)

^^^

   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/query.py",
 line 1805, in _insert

 return query.get_compiler(using=using).execute_sql(returning_fields)

^

   File
 "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/sql/compiler.py",
 line 1820, in execute_sql

 

Re: testing newbie - help requested: app works, tests give errors

2023-05-10 Thread 'Bob Aalsma' via Django users
Sorry Vishesh, thanks for the quick answer but I have no idea what you mean.

On Wednesday, May 10, 2023 at 2:00:51 PM UTC+2 Vishesh Mangla wrote:

> False or True check for yourself.
>
> On Wed, 10 May, 2023, 17:29 Vishesh Mangla,  wrote:
>
>> It looks like you are passing a null but null=False is not set
>>
>> On Wed, 10 May, 2023, 17:27 'Bob Aalsma' via Django users, <
>> django...@googlegroups.com> wrote:
>>
>>> I'm trying to test a django-admin command and don't understand why the 
>>> tests give errors on the code while the code works as expected.
>>>
>>> I'm under the impression that the *raise CommandError* is ignored by 
>>> the test, but don't understand why this would be.
>>>
>>> Please help.
>>>
>>> Running the code shows:
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> populate_source 0
>>>
>>> *CommandError: Alleen hele getallen > 0 toegestaan*
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> populate_source 1
>>>
>>> *Teksten zijn gegenereerd voor tekstlengte 1*
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> populate_source 1
>>>
>>> *CommandError: Teksten voor nummer 1 zijn al eerder gegenereerd*
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py 
>>> populate_source 7
>>>
>>> *CommandError: Opgegeven sleutel 7 niet gevonden*
>>>
>>> Running the tests shows
>>>
>>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py test 
>>> tests.test_sources_app_command_populate
>>>
>>> Found 3 test(s).
>>>
>>> Creating test database for alias 'default'...
>>>
>>> System check identified no issues (0 silenced).
>>>
>>> EEE
>>>
>>> ==
>>>
>>> ERROR: test_command_output_been_there 
>>> (tests.test_sources_app_command_populate.PopulateSourceTests.test_command_output_been_there)
>>>
>>> Test for failure: in_use = True.
>>>
>>> --
>>>
>>> Traceback (most recent call last):
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
>>>  
>>> line 89, in _execute
>>>
>>> return self.cursor.execute(sql, params)
>>>
>>>
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py",
>>>  
>>> line 328, in execute
>>>
>>> return super().execute(query, params)
>>>
>>>^^
>>>
>>> sqlite3.IntegrityError: NOT NULL constraint failed: 
>>> domain_sources_app_characternumber.number_of_combinations
>>>
>>>
>>> The above exception was the direct cause of the following exception:
>>>
>>>
>>> Traceback (most recent call last):
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/tests/test_sources_app_command_populate.py",
>>>  
>>> line 30, in test_command_output_been_there
>>>
>>> thingy.save()
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>>  
>>> line 814, in save
>>>
>>> self.save_base(
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>>  
>>> line 877, in save_base
>>>
>>> updated = self._save_table(
>>>
>>>   ^
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>>  
>>> line 1020, in _save_table
>>>
>>> results = self._do_insert(
>>>
>>>   
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>>>  
>>> line 1061, in _do_insert
>>>
>>> return manager._insert(
>>>
>>>
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/manager.py",
>>>  
>>> line 87, in manager_method
>>>
>>> return getattr(self.get_queryset(), name)(*args, **kwargs)
>>>
>>>^^^
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/query.py",
>>>  
>>> line 1805, in _insert
>>>
>>> return query.get_compiler(using=using).execute_sql(returning_fields)
>>>
>>>^
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/sql/compiler.py",
>>>  
>>> line 1820, in execute_sql
>>>
>>> cursor.execute(sql, params)
>>>
>>>   File 
>>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
>>>  
>>> line 67, in execute
>>>
>>> return self._execute_with_wrappers(
>>>
>>>
>>>
>>>   File 
>>> 

Re: testing newbie - help requested: app works, tests give errors

2023-05-10 Thread Vishesh Mangla
False or True check for yourself.

On Wed, 10 May, 2023, 17:29 Vishesh Mangla, 
wrote:

> It looks like you are passing a null but null=False is not set
>
> On Wed, 10 May, 2023, 17:27 'Bob Aalsma' via Django users, <
> django-users@googlegroups.com> wrote:
>
>> I'm trying to test a django-admin command and don't understand why the
>> tests give errors on the code while the code works as expected.
>>
>> I'm under the impression that the *raise CommandError* is ignored by the
>> test, but don't understand why this would be.
>>
>> Please help.
>>
>> Running the code shows:
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
>> populate_source 0
>>
>> *CommandError: Alleen hele getallen > 0 toegestaan*
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
>> populate_source 1
>>
>> *Teksten zijn gegenereerd voor tekstlengte 1*
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
>> populate_source 1
>>
>> *CommandError: Teksten voor nummer 1 zijn al eerder gegenereerd*
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
>> populate_source 7
>>
>> *CommandError: Opgegeven sleutel 7 niet gevonden*
>>
>> Running the tests shows
>>
>> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py test
>> tests.test_sources_app_command_populate
>>
>> Found 3 test(s).
>>
>> Creating test database for alias 'default'...
>>
>> System check identified no issues (0 silenced).
>>
>> EEE
>>
>> ==
>>
>> ERROR: test_command_output_been_there
>> (tests.test_sources_app_command_populate.PopulateSourceTests.test_command_output_been_there)
>>
>> Test for failure: in_use = True.
>>
>> --
>>
>> Traceback (most recent call last):
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
>> line 89, in _execute
>>
>> return self.cursor.execute(sql, params)
>>
>>
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py",
>> line 328, in execute
>>
>> return super().execute(query, params)
>>
>>^^
>>
>> sqlite3.IntegrityError: NOT NULL constraint failed:
>> domain_sources_app_characternumber.number_of_combinations
>>
>>
>> The above exception was the direct cause of the following exception:
>>
>>
>> Traceback (most recent call last):
>>
>>   File
>> "/Users/werker/Projects/domain_reader/tests/test_sources_app_command_populate.py",
>> line 30, in test_command_output_been_there
>>
>> thingy.save()
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>> line 814, in save
>>
>> self.save_base(
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>> line 877, in save_base
>>
>> updated = self._save_table(
>>
>>   ^
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>> line 1020, in _save_table
>>
>> results = self._do_insert(
>>
>>   
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
>> line 1061, in _do_insert
>>
>> return manager._insert(
>>
>>
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/manager.py",
>> line 87, in manager_method
>>
>> return getattr(self.get_queryset(), name)(*args, **kwargs)
>>
>>^^^
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/query.py",
>> line 1805, in _insert
>>
>> return query.get_compiler(using=using).execute_sql(returning_fields)
>>
>>^
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/sql/compiler.py",
>> line 1820, in execute_sql
>>
>> cursor.execute(sql, params)
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
>> line 67, in execute
>>
>> return self._execute_with_wrappers(
>>
>>
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
>> line 80, in _execute_with_wrappers
>>
>> return executor(sql, params, many, context)
>>
>>
>>
>>   File
>> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
>> line 84, in _execute
>>
>> with 

Re: testing newbie - help requested: app works, tests give errors

2023-05-10 Thread Vishesh Mangla
It looks like you are passing a null but null=False is not set

On Wed, 10 May, 2023, 17:27 'Bob Aalsma' via Django users, <
django-users@googlegroups.com> wrote:

> I'm trying to test a django-admin command and don't understand why the
> tests give errors on the code while the code works as expected.
>
> I'm under the impression that the *raise CommandError* is ignored by the
> test, but don't understand why this would be.
>
> Please help.
>
> Running the code shows:
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> populate_source 0
>
> *CommandError: Alleen hele getallen > 0 toegestaan*
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> populate_source 1
>
> *Teksten zijn gegenereerd voor tekstlengte 1*
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> populate_source 1
>
> *CommandError: Teksten voor nummer 1 zijn al eerder gegenereerd*
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py
> populate_source 7
>
> *CommandError: Opgegeven sleutel 7 niet gevonden*
>
> Running the tests shows
>
> (.venv) werker@Werkers-Mac-mini domain_reader % python3 manage.py test
> tests.test_sources_app_command_populate
>
> Found 3 test(s).
>
> Creating test database for alias 'default'...
>
> System check identified no issues (0 silenced).
>
> EEE
>
> ==
>
> ERROR: test_command_output_been_there
> (tests.test_sources_app_command_populate.PopulateSourceTests.test_command_output_been_there)
>
> Test for failure: in_use = True.
>
> --
>
> Traceback (most recent call last):
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
> line 89, in _execute
>
> return self.cursor.execute(sql, params)
>
>
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py",
> line 328, in execute
>
> return super().execute(query, params)
>
>^^
>
> sqlite3.IntegrityError: NOT NULL constraint failed:
> domain_sources_app_characternumber.number_of_combinations
>
>
> The above exception was the direct cause of the following exception:
>
>
> Traceback (most recent call last):
>
>   File
> "/Users/werker/Projects/domain_reader/tests/test_sources_app_command_populate.py",
> line 30, in test_command_output_been_there
>
> thingy.save()
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
> line 814, in save
>
> self.save_base(
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
> line 877, in save_base
>
> updated = self._save_table(
>
>   ^
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
> line 1020, in _save_table
>
> results = self._do_insert(
>
>   
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/base.py",
> line 1061, in _do_insert
>
> return manager._insert(
>
>
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/manager.py",
> line 87, in manager_method
>
> return getattr(self.get_queryset(), name)(*args, **kwargs)
>
>^^^
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/query.py",
> line 1805, in _insert
>
> return query.get_compiler(using=using).execute_sql(returning_fields)
>
>^
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/models/sql/compiler.py",
> line 1820, in execute_sql
>
> cursor.execute(sql, params)
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
> line 67, in execute
>
> return self._execute_with_wrappers(
>
>
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
> line 80, in _execute_with_wrappers
>
> return executor(sql, params, many, context)
>
>
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/backends/utils.py",
> line 84, in _execute
>
> with self.db.wrap_database_errors:
>
>   File
> "/Users/werker/Projects/domain_reader/.venv/lib/python3.11/site-packages/django/db/utils.py",
> line 91, in __exit__
>
> raise dj_exc_value.with_traceback(traceback) from exc_value
>
>   File
> 

Re: Testing django

2023-03-16 Thread Ayush Bisht
Yeah, I got you..
My concern is on the documentation, the way it has provided the commands
for executing test cases.

That
path.to.settings seems confusing sometimes..

On Fri, 17 Mar, 2023, 1:20 am Bhuvnesh Sharma, 
wrote:

> We can run django tests with custom settings by using --settings flag and
> providing the path to the custom settings file . For example:
> ./runtests.py --settings=new_app.test_settings
>
> What do you want to do exactly?
>
> On Fri, Mar 17, 2023 at 1:00 AM Ayush Bisht 
> wrote:
>
>> Seems like, it is for defining how actually we are selecting the specific
>> test case. It is very confusing at first.
>> Can't we just explain it with an example..
>>
>> On Friday, March 17, 2023 at 12:54:27 AM UTC+5:30 Ayush Bisht wrote:
>>
>>> * ./runtests.py --settings=path.to.settings i18n.tests.TranslationTests*
>>>
>>> what exactly is the purpose of *path.to.settings,* I'm getting an error
>>> while running the above line.
>>> Can anyone please explain?
>>>
>>> *Error*
>>> Testing against Django installed in '/home/ayush/OS/django/django' with
>>> up to 8 processes
>>> Traceback (most recent call last):
>>>   File "/home/ayush/OS/django/tests/./runtests.py", line 770, in 
>>> failures = django_tests(
>>>   File "/home/ayush/OS/django/tests/./runtests.py", line 398, in
>>> django_tests
>>> test_labels, state = setup_run_tests(*process_setup_args)
>>>   File "/home/ayush/OS/django/tests/./runtests.py", line 300, in
>>> setup_run_tests
>>> test_modules, state = setup_collect_tests(
>>>   File "/home/ayush/OS/django/tests/./runtests.py", line 201, in
>>> setup_collect_tests
>>> "INSTALLED_APPS": settings.INSTALLED_APPS,
>>>   File "/home/ayush/OS/django/django/conf/__init__.py", line 84, in
>>> __getattr__
>>> self._setup(name)
>>>   File "/home/ayush/OS/django/django/conf/__init__.py", line 71, in
>>> _setup
>>> self._wrapped = Settings(settings_module)
>>>   File "/home/ayush/OS/django/django/conf/__init__.py", line 185, in
>>> __init__
>>> mod = importlib.import_module(self.SETTINGS_MODULE)
>>>   File "/usr/lib/python3.10/importlib/__init__.py", line 126, in
>>> import_module
>>> return _bootstrap._gcd_import(name[level:], package, level)
>>>   File "", line 1050, in _gcd_import
>>>   File "", line 1027, in _find_and_load
>>>   File "", line 992, in
>>> _find_and_load_unlocked
>>>   File "", line 241, in
>>> _call_with_frames_removed
>>>   File "", line 1050, in _gcd_import
>>>   File "", line 1027, in _find_and_load
>>>   File "", line 992, in
>>> _find_and_load_unlocked
>>>   File "", line 241, in
>>> _call_with_frames_removed
>>>   File "", line 1050, in _gcd_import
>>>   File "", line 1027, in _find_and_load
>>>   File "", line 1004, in
>>> _find_and_load_unlocked
>>> ModuleNotFoundError: No module named 'path'
>>>
>> --
>> 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/dd827ca8-704e-4ffc-8d7a-2c56d100cdd7n%40googlegroups.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/CA%2BZJHEqMWEj8dE9gpVW0f5QajXy1b9GPp-Qur4457GMoWAoUbQ%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/CA%2B%2BM4H5-M%2B6T5PvfctNYJR7o0ebry_4f-JUGec8QewJs%2BhASNg%40mail.gmail.com.


Re: Testing django

2023-03-16 Thread Bhuvnesh Sharma
We can run django tests with custom settings by using --settings flag and
providing the path to the custom settings file . For example:
./runtests.py --settings=new_app.test_settings

What do you want to do exactly?

On Fri, Mar 17, 2023 at 1:00 AM Ayush Bisht 
wrote:

> Seems like, it is for defining how actually we are selecting the specific
> test case. It is very confusing at first.
> Can't we just explain it with an example..
>
> On Friday, March 17, 2023 at 12:54:27 AM UTC+5:30 Ayush Bisht wrote:
>
>> * ./runtests.py --settings=path.to.settings i18n.tests.TranslationTests*
>>
>> what exactly is the purpose of *path.to.settings,* I'm getting an error
>> while running the above line.
>> Can anyone please explain?
>>
>> *Error*
>> Testing against Django installed in '/home/ayush/OS/django/django' with
>> up to 8 processes
>> Traceback (most recent call last):
>>   File "/home/ayush/OS/django/tests/./runtests.py", line 770, in 
>> failures = django_tests(
>>   File "/home/ayush/OS/django/tests/./runtests.py", line 398, in
>> django_tests
>> test_labels, state = setup_run_tests(*process_setup_args)
>>   File "/home/ayush/OS/django/tests/./runtests.py", line 300, in
>> setup_run_tests
>> test_modules, state = setup_collect_tests(
>>   File "/home/ayush/OS/django/tests/./runtests.py", line 201, in
>> setup_collect_tests
>> "INSTALLED_APPS": settings.INSTALLED_APPS,
>>   File "/home/ayush/OS/django/django/conf/__init__.py", line 84, in
>> __getattr__
>> self._setup(name)
>>   File "/home/ayush/OS/django/django/conf/__init__.py", line 71, in _setup
>> self._wrapped = Settings(settings_module)
>>   File "/home/ayush/OS/django/django/conf/__init__.py", line 185, in
>> __init__
>> mod = importlib.import_module(self.SETTINGS_MODULE)
>>   File "/usr/lib/python3.10/importlib/__init__.py", line 126, in
>> import_module
>> return _bootstrap._gcd_import(name[level:], package, level)
>>   File "", line 1050, in _gcd_import
>>   File "", line 1027, in _find_and_load
>>   File "", line 992, in
>> _find_and_load_unlocked
>>   File "", line 241, in
>> _call_with_frames_removed
>>   File "", line 1050, in _gcd_import
>>   File "", line 1027, in _find_and_load
>>   File "", line 992, in
>> _find_and_load_unlocked
>>   File "", line 241, in
>> _call_with_frames_removed
>>   File "", line 1050, in _gcd_import
>>   File "", line 1027, in _find_and_load
>>   File "", line 1004, in
>> _find_and_load_unlocked
>> ModuleNotFoundError: No module named 'path'
>>
> --
> 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/dd827ca8-704e-4ffc-8d7a-2c56d100cdd7n%40googlegroups.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/CA%2BZJHEqMWEj8dE9gpVW0f5QajXy1b9GPp-Qur4457GMoWAoUbQ%40mail.gmail.com.


Re: Testing django

2023-03-16 Thread Ayush Bisht
Seems like, it is for defining how actually we are selecting the specific 
test case. It is very confusing at first. 
Can't we just explain it with an example..

On Friday, March 17, 2023 at 12:54:27 AM UTC+5:30 Ayush Bisht wrote:

> * ./runtests.py --settings=path.to.settings i18n.tests.TranslationTests*
>
> what exactly is the purpose of *path.to.settings,* I'm getting an error 
> while running the above line.
> Can anyone please explain?
>
> *Error*  
> Testing against Django installed in '/home/ayush/OS/django/django' with up 
> to 8 processes
> Traceback (most recent call last):
>   File "/home/ayush/OS/django/tests/./runtests.py", line 770, in 
> failures = django_tests(
>   File "/home/ayush/OS/django/tests/./runtests.py", line 398, in 
> django_tests
> test_labels, state = setup_run_tests(*process_setup_args)
>   File "/home/ayush/OS/django/tests/./runtests.py", line 300, in 
> setup_run_tests
> test_modules, state = setup_collect_tests(
>   File "/home/ayush/OS/django/tests/./runtests.py", line 201, in 
> setup_collect_tests
> "INSTALLED_APPS": settings.INSTALLED_APPS,
>   File "/home/ayush/OS/django/django/conf/__init__.py", line 84, in 
> __getattr__
> self._setup(name)
>   File "/home/ayush/OS/django/django/conf/__init__.py", line 71, in _setup
> self._wrapped = Settings(settings_module)
>   File "/home/ayush/OS/django/django/conf/__init__.py", line 185, in 
> __init__
> mod = importlib.import_module(self.SETTINGS_MODULE)
>   File "/usr/lib/python3.10/importlib/__init__.py", line 126, in 
> import_module
> return _bootstrap._gcd_import(name[level:], package, level)
>   File "", line 1050, in _gcd_import
>   File "", line 1027, in _find_and_load
>   File "", line 992, in 
> _find_and_load_unlocked
>   File "", line 241, in 
> _call_with_frames_removed
>   File "", line 1050, in _gcd_import
>   File "", line 1027, in _find_and_load
>   File "", line 992, in 
> _find_and_load_unlocked
>   File "", line 241, in 
> _call_with_frames_removed
>   File "", line 1050, in _gcd_import
>   File "", line 1027, in _find_and_load
>   File "", line 1004, in 
> _find_and_load_unlocked
> ModuleNotFoundError: No module named 'path'
>

-- 
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/dd827ca8-704e-4ffc-8d7a-2c56d100cdd7n%40googlegroups.com.


Re: Testing Django User Login Form

2021-04-23 Thread lone...@gmail.com
Thank you for the reply!  I will totally try this tonight!

On Thursday, April 22, 2021 at 7:31:40 PM UTC-4 David Nugent wrote:

> Try creating a request using RequestFactory and use that to input the 
> credentials. I don't think the way you are creating the form is valid.
>
> rf = RequestFactory()
> request = rf.post('/some_mock_url', dict(username='abc', 
> password='password'))
> form = AuthenticationForm(request)
>
>

-- 
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/e3079f83-6175-4852-9a6a-f94625079af4n%40googlegroups.com.


Re: Testing Django User Login Form

2021-04-22 Thread David Nugent
Try creating a request using RequestFactory and use that to input the
credentials. I don't think the way you are creating the form is valid.

rf = RequestFactory()
request = rf.post('/some_mock_url', dict(username='abc',
password='password'))
form = AuthenticationForm(request)

-- 
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/CAE5VhgWBM7dqPBzMc4P8eGCOuksM54kcnPnVA83ciE93C6bqWw%40mail.gmail.com.


Re: Testing my Django App

2020-03-23 Thread Motaz Hejaze
Delete the sqlite database and migrate again to remake it

On Mon, 23 Mar 2020, 7:56 pm victor awakan,  wrote:

> Check your book.user_id. It shouldn’t be null. That’s what the last error
> is saying.
>
> On Mon 23. Mar 2020 at 17.44, Ejike Enyinnaya 
> wrote:
>
>> Good day All,
>>
>> I am currently running a test for my Django app call 'Books'.
>>
>> Anytime I run an INDEX test, I get the following error below:
>>
>> "File
>> "/Users/macbookpro/.local/share/virtualenvs/first_django_app-mymO4nCn/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py",
>> line 396, in execute
>> return Database.Cursor.execute(self, query, params)
>> django.db.utils.IntegrityError: NOT NULL constraint failed:
>> books_book.user_id"
>>
>> Please can anyone point to what the issue is or what I am doing wrong.
>>
>> Thanks and Regards,
>>
>> --
>> 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/6de24eab-953f-49b9-9dc4-7aa65dc9e229%40googlegroups.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/CAAipwd_qa%3DVbB0XLQ%3D-93XrqWV%3D6OY9%2BKNWUTD5HJ2yRfac24w%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/CAHV4E-dKnqSzAJnxmtSPFJPQNQ7bVgPQC%2Bv9xiN2ZTOzV2VCaA%40mail.gmail.com.


Re: Testing my Django App

2020-03-23 Thread victor awakan
Check your book.user_id. It shouldn’t be null. That’s what the last error
is saying.

On Mon 23. Mar 2020 at 17.44, Ejike Enyinnaya 
wrote:

> Good day All,
>
> I am currently running a test for my Django app call 'Books'.
>
> Anytime I run an INDEX test, I get the following error below:
>
> "File
> "/Users/macbookpro/.local/share/virtualenvs/first_django_app-mymO4nCn/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py",
> line 396, in execute
> return Database.Cursor.execute(self, query, params)
> django.db.utils.IntegrityError: NOT NULL constraint failed:
> books_book.user_id"
>
> Please can anyone point to what the issue is or what I am doing wrong.
>
> Thanks and Regards,
>
> --
> 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/6de24eab-953f-49b9-9dc4-7aa65dc9e229%40googlegroups.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/CAAipwd_qa%3DVbB0XLQ%3D-93XrqWV%3D6OY9%2BKNWUTD5HJ2yRfac24w%40mail.gmail.com.


Re: Testing - get_object_or_404 returns 200 status code

2019-06-10 Thread Cristhiam Gabriel Fernández
Hi RyuCoder

Should not get_object_or_404 shortcut retry 404 status code?

El lunes, 10 de junio de 2019, 15:29:24 (UTC-5), RyuCoder escribió:
>
> Whats your question?
> I failed to understand that 
>
> On Tue, Jun 11, 2019, 1:45 AM Cristhiam Gabriel Fernández <
> cristh...@gmail.com > wrote:
>
>> Hi Django super heroes
>>
>> I'm making of test cases for my simple Django application. When I test a 
>> view with get_object_or_404 shortcut it returns 200 status code.
>>
>> def my_view(self, request):
>>   obj_id = request.POST.get('id')
>>   obj = get_object_or_404(MyModel, pk=id)
>>   
>>
>>
>> # Test case
>> ...data = {'id': 999}
>>  response = self.client.post(reverse('view.name'), data=data)
>>  self.assertEqual(response.status_code, 404)
>>
>>
>> I'm getting *AssertionError: 200 != 404*
>>
>> -- 
>> 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...@googlegroups.com .
>> To post to this group, send email to django...@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/488aa077-1b11-4404-8d4e-0dad1885707b%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/c6605bef-45e0-431f-8861-f4b3e38f8856%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing - get_object_or_404 returns 200 status code

2019-06-10 Thread Chetan Ganji
Whats your question?
I failed to understand that 

On Tue, Jun 11, 2019, 1:45 AM Cristhiam Gabriel Fernández <
cristhiang...@gmail.com> wrote:

> Hi Django super heroes
>
> I'm making of test cases for my simple Django application. When I test a
> view with get_object_or_404 shortcut it returns 200 status code.
>
> def my_view(self, request):
>   obj_id = request.POST.get('id')
>   obj = get_object_or_404(MyModel, pk=id)
>   
>
>
> # Test case
> ...data = {'id': 999}
>  response = self.client.post(reverse('view.name'), data=data)
>  self.assertEqual(response.status_code, 404)
>
>
> I'm getting *AssertionError: 200 != 404*
>
> --
> 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/488aa077-1b11-4404-8d4e-0dad1885707b%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/CAMKMUjsTgjvtxO84VRLwz6sAc6YSXVMguQGXRHPjoehMYD8W-g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing API

2019-04-22 Thread Jani Tiainen
Hi,

DRF does have built-in API viewer. To enable that you need to add
rest_framework app in your INSTALLED_APPS so it can find necessary
templates for showing.

On Tue, Apr 23, 2019 at 7:15 AM Shubham Joshi  wrote:

> I have created the custom model authentication in django rest , so far I
> dont have front end , so my question is , Im I done with the API, since on
> browser it gives an error TemplateDoesNotExist at /
> rest_framework/api.html that of course due to I dont have template, in
> postmen its giving {
> "detail": "Method \"GET\" not allowed."
> } , Am I going right?
>
> https://github.com/shubham1507/school
> 
>
> --
> 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/5596723f-0358-41b5-9b0f-cf0f9dc84057%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>


-- 
Jani Tiainen
Software wizard

https://blog.jani.tiainen.cc/

Always open for short term jobs or contracts to work with Django.

-- 
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/CAHn91ocacYW95Gq%3DwH9DrWZMFjN9mWu_xEssBo%2BePh_VhbHStQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing Channels 2.0 consumers - problem with routing

2018-02-11 Thread Andrew Godwin
Hi,

This is a known issue with the Redis backend -
https://github.com/django/channels/issues/859

I am looking at it today.

Andrew

On Sun, Feb 11, 2018 at 8:54 AM, Azamat Galimzhanov 
wrote:

> After fixing this issue, here is the updated consumer:
>
>
> from functools import lru_cache
>
> from asgiref.sync import AsyncToSync
> from channels.generic.websocket import WebsocketConsumer
>
>
> class AuctionConsumer(WebsocketConsumer):
> @property
> @lru_cache(maxsize=None)
> def group_name(self):
> path = self.scope['path']
> auction_id = path[len('auctions/'):-1]
> return 'auction_{}'.format(auction_id)
>
> def connect(self):
> AsyncToSync(self.channel_layer.group_add)(self.group_name, 
> self.channel_name)
> self.accept()
>
> def disconnect(self, close_code):
> AsyncToSync(self.channel_layer.group_discard)(self.group_name, 
> self.channel_name)
>
> def receive(self, text_data):
> AsyncToSync(self.channel_layer.group_send)(
> self.group_name,
> {
> 'type': 'auction.bid',
> 'text': text_data,
> },
> )
>
> def auction_bid(self, event):
> self.send(text_data=event['text'])
>
>
>  some of my other tests seem to have influence test_consumers, so I set up
> a simplified test case, here it is:
>
> from channels.layers import get_channel_layer
> from asgiref.sync import AsyncToSync
>
> import pytest
> from channels.testing import WebsocketCommunicator
> from auctions.consumers import AuctionConsumer
>
>
> def test_A():
> channel_layer = get_channel_layer()
> AsyncToSync(channel_layer.group_send)(
> 'auction_1',
> {
> 'type': 'auction.bid',
> 'text': '1'
> }
> )
>
>
> @pytest.mark.asyncio
> async def test_B():
> communicator = WebsocketCommunicator(AuctionConsumer, 'auctions/1/')
> connected, subprotocol = await communicator.connect()
> assert connected
> # Test sending text
> await communicator.send_to(text_data='1')
> response = await communicator.receive_from()
> assert response == '1'
> # Close
> await communicator.disconnect()
>
>
> And individually they pass:
>
>  !  ◰³ django_root-FXsg3jFU  /m/k/D/d/auction   41/bidding_websockets
> *…  django_root  pytest -v -s auctions/tests/test_test.py::test_A
>   5.8s  Sun 11 Feb 2018 10:46:12 PM +06
> 
> === test session starts
> 
> ===
> platform linux -- Python 3.6.3, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 --
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/bin/python3.6m
> cachedir: .pytest_cache
> Django settings: core.settings (from ini file)
> rootdir: /media/khazidhea/Data/dev/auction/django_root, inifile: setup.cfg
> plugins: mock-1.6.3, flake8-0.9.1, django-3.1.2, cov-2.5.1, asyncio-0.8.0,
> celery-4.1.0
> collected 1 item
>
>
>
> auctions/tests/test_test.py::test_A PASSED
>
> 
>  1 passed in 0.07 seconds
> 
> =
>  ◰³ django_root-FXsg3jFU  /m/k/D/d/auction   41/bidding_websockets *… 
> django_root  pytest -v -s auctions/tests/test_test.py::test_B
>   4053ms  Sun 11 Feb 2018 10:46:20 PM +06
> 
> === test session starts
> 
> ===
> platform linux -- Python 3.6.3, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 --
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/bin/python3.6m
> cachedir: .pytest_cache
> Django settings: core.settings (from ini file)
> rootdir: /media/khazidhea/Data/dev/auction/django_root, inifile: setup.cfg
> plugins: mock-1.6.3, flake8-0.9.1, django-3.1.2, cov-2.5.1, asyncio-0.8.0,
> celery-4.1.0
> collected 1 item
>
>
>
> auctions/tests/test_test.py::test_B PASSED
>
> 
>  1 passed in 0.09 seconds
> 
> =
> Task was destroyed but it is pending!
> task:  /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/aioredis/connection.py:175>
> wait_for= 0x7f19b9b6bbe8>()]> cb=[Future.set_result()]>
>
>
>
>
> But when I run both (I think specifically when B is run after A) I get a
> huge traceback with this in the end:
>
> def _check_closed(self):
> if self._closed:
> >   raise RuntimeError('Event loop is 

Re: Testing Channels 2.0 consumers - problem with routing

2018-02-11 Thread Azamat Galimzhanov
After fixing this issue, here is the updated consumer:


from functools import lru_cache

from asgiref.sync import AsyncToSync
from channels.generic.websocket import WebsocketConsumer


class AuctionConsumer(WebsocketConsumer):
@property
@lru_cache(maxsize=None)
def group_name(self):
path = self.scope['path']
auction_id = path[len('auctions/'):-1]
return 'auction_{}'.format(auction_id)

def connect(self):
AsyncToSync(self.channel_layer.group_add)(self.group_name, 
self.channel_name)
self.accept()

def disconnect(self, close_code):
AsyncToSync(self.channel_layer.group_discard)(self.group_name, 
self.channel_name)

def receive(self, text_data):
AsyncToSync(self.channel_layer.group_send)(
self.group_name,
{
'type': 'auction.bid',
'text': text_data,
},
)

def auction_bid(self, event):
self.send(text_data=event['text'])


 some of my other tests seem to have influence test_consumers, so I set up 
a simplified test case, here it is:

from channels.layers import get_channel_layer
from asgiref.sync import AsyncToSync

import pytest
from channels.testing import WebsocketCommunicator
from auctions.consumers import AuctionConsumer


def test_A():
channel_layer = get_channel_layer()
AsyncToSync(channel_layer.group_send)(
'auction_1',
{
'type': 'auction.bid',
'text': '1'
}
)


@pytest.mark.asyncio
async def test_B():
communicator = WebsocketCommunicator(AuctionConsumer, 'auctions/1/')
connected, subprotocol = await communicator.connect()
assert connected
# Test sending text
await communicator.send_to(text_data='1')
response = await communicator.receive_from()
assert response == '1'
# Close
await communicator.disconnect()


And individually they pass:

 !  ◰³ django_root-FXsg3jFU  /m/k/D/d/auction   41/bidding_websockets 
*…  django_root  pytest -v -s auctions/tests/test_test.py::test_A
5.8s  Sun 11 Feb 2018 10:46:12 PM +06
===
 
test session starts 
===
platform linux -- Python 3.6.3, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 -- 
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/bin/python3.6m
cachedir: .pytest_cache
Django settings: core.settings (from ini file)
rootdir: /media/khazidhea/Data/dev/auction/django_root, inifile: setup.cfg
plugins: mock-1.6.3, flake8-0.9.1, django-3.1.2, cov-2.5.1, asyncio-0.8.0, 
celery-4.1.0
collected 1 item

  

auctions/tests/test_test.py::test_A PASSED


 
1 passed in 0.07 seconds 
=
 ◰³ django_root-FXsg3jFU  /m/k/D/d/auction   41/bidding_websockets *…  
django_root  pytest -v -s auctions/tests/test_test.py::test_B  
4053ms  Sun 11 Feb 2018 10:46:20 PM +06
===
 
test session starts 
===
platform linux -- Python 3.6.3, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 -- 
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/bin/python3.6m
cachedir: .pytest_cache
Django settings: core.settings (from ini file)
rootdir: /media/khazidhea/Data/dev/auction/django_root, inifile: setup.cfg
plugins: mock-1.6.3, flake8-0.9.1, django-3.1.2, cov-2.5.1, asyncio-0.8.0, 
celery-4.1.0
collected 1 item

  

auctions/tests/test_test.py::test_B PASSED


 
1 passed in 0.09 seconds 
=
Task was destroyed but it is pending!
task: 
 
wait_for=()]> cb=[Future.set_result()]>




But when I run both (I think specifically when B is run after A) I get a 
huge traceback with this in the end:

def _check_closed(self):
if self._closed:
>   raise RuntimeError('Event loop is closed')
E   RuntimeError: Event loop is closed


Full stack trace is here: https://pastebin.com/ZeiMVZD7

Why could it be?

On Saturday, February 10, 2018 at 12:03:53 AM UTC+6, 

Re: Testing Channels 2.0 consumers - problem with routing

2018-02-09 Thread Andrew Godwin
A disconnect() method in your generic consumer takes one argument, a
`close_code` - add that in to your function and it will fix it.

Feel free to continue problems in this thread, or you can also use GitHub
issues on the channels project if you think they're actual bugs!

Andrew

On Fri, Feb 9, 2018 at 3:58 AM, Azamat Galimzhanov 
wrote:

> Thanks for reply!
>
> self.scope looks like this:
>
> {'type': 'websocket', 'path': 'auctions/1/', 'headers': [],
> 'subprotocols': []}
>
> I am not sure why url_route is not there. I rewrote my group_name code to
> use path instead and now this part works.
>
> There is a new error though, during disconnect, when calling this part of
> the test:
>
> await communicator.disconnect()
>
>
> Here is disconnect method of my consumer, but I think the problem isnt
> here:
>
> def disconnect(self):
> AsyncToSync(self.channel_layer.group_discard)(self.group_name, 
> self.channel_name)
>
>
> This is the pytest output:
>
> >   await communicator.disconnect()
>
> auctions/tests/test_consumers.py:18:
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/channels/testing/websocket.py:100:
> in disconnect
> await self.future
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/channels/consumer.py:53: in __call__
> await await_many_dispatch([receive, self.channel_receive],
> self.dispatch)
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/channels/utils.py:48: in
> await_many_dispatch
> await dispatch(result)
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/asgiref/sync.py:103: in inner
> return await async_func(*args, **kwargs)
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/asgiref/sync.py:83: in __call__
> return await asyncio.wait_for(future, timeout=None)
> /usr/lib/python3.6/asyncio/tasks.py:339: in wait_for
> return (yield from fut)
> /usr/lib/python3.6/concurrent/futures/thread.py:56: in run
> result = self.fn(*self.args, **self.kwargs)
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/asgiref/sync.py:95: in thread_handler
> raise e
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/asgiref/sync.py:93: in thread_handler
> self.func(*args, **kwargs)
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/channels/consumer.py:98: in dispatch
> handler(message)
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
> self = ,
> message = {'code': 1000, 'type': 'websocket.disconnect'}
>
> def websocket_disconnect(self, message):
> """
> Called when a WebSocket connection is closed. Base level so
> you don't
> need to call super() all the time.
> """
> # TODO: group leaving
> >   self.disconnect(message["code"])
> E   TypeError: disconnect() takes 1 positional argument but 2 were
> given
>
> /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/channels/generic/websocket.py:86:
> TypeError
> 
>  1 failed in 0.36 seconds
> 
> =
> Task was destroyed but it is pending!
> task:  /home/khazidhea/.local/share/virtualenvs/django_root-
> FXsg3jFU/lib/python3.6/site-packages/aioredis/connection.py:181>
> wait_for= 0x7f098d344ac8>()]> cb=[Future.set_result()]>
>
>
>
> P.S. I have a couple more problems with testing this particular project
> related to channels. For example I tried ignoring this disconnect problem,
> this test passed with 99% coverage, but when I run the whole test suite it
> breaks and I figured out what other tests break this one, but not sure why.
> Would you mind looking at this too? If yes, should I create a new thread or
> continue in this one?
>
>
> On Thursday, February 8, 2018 at 4:07:38 AM UTC+6, Andrew Godwin wrote:
>>
>> I'm not going to address the mocking, as there's subtle details there
>> (e.g. you mocked group_name as a non-property, I think), but look at the
>> main issue.
>>
>> Can you make your code print out what _is_ in `self.scope`? url_route
>> should definitely be in there, but I am curious what it looks like if it is
>> not.
>>
>> Andrew
>>
>> On Wed, Feb 7, 2018 at 12:16 PM, 

Re: Testing Channels 2.0 consumers - problem with routing

2018-02-09 Thread Azamat Galimzhanov
Thanks for reply!

self.scope looks like this:

{'type': 'websocket', 'path': 'auctions/1/', 'headers': [], 'subprotocols': 
[]}

I am not sure why url_route is not there. I rewrote my group_name code to 
use path instead and now this part works.

There is a new error though, during disconnect, when calling this part of 
the test:

await communicator.disconnect()


Here is disconnect method of my consumer, but I think the problem isnt here:

def disconnect(self):
AsyncToSync(self.channel_layer.group_discard)(self.group_name, 
self.channel_name)


This is the pytest output:

>   await communicator.disconnect()

auctions/tests/test_consumers.py:18: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/channels/testing/websocket.py:100:
 
in disconnect
await self.future
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/channels/consumer.py:53:
 
in __call__
await await_many_dispatch([receive, self.channel_receive], 
self.dispatch)
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/channels/utils.py:48:
 
in await_many_dispatch
await dispatch(result)
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/asgiref/sync.py:103:
 
in inner
return await async_func(*args, **kwargs)
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/asgiref/sync.py:83:
 
in __call__
return await asyncio.wait_for(future, timeout=None)
/usr/lib/python3.6/asyncio/tasks.py:339: in wait_for
return (yield from fut)
/usr/lib/python3.6/concurrent/futures/thread.py:56: in run
result = self.fn(*self.args, **self.kwargs)
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/asgiref/sync.py:95:
 
in thread_handler
raise e
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/asgiref/sync.py:93:
 
in thread_handler
self.func(*args, **kwargs)
/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/channels/consumer.py:98:
 
in dispatch
handler(message)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = , 
message = {'code': 1000, 'type': 'websocket.disconnect'}

def websocket_disconnect(self, message):
"""
Called when a WebSocket connection is closed. Base level so you 
don't
need to call super() all the time.
"""
# TODO: group leaving
>   self.disconnect(message["code"])
E   TypeError: disconnect() takes 1 positional argument but 2 were given

/home/khazidhea/.local/share/virtualenvs/django_root-FXsg3jFU/lib/python3.6/site-packages/channels/generic/websocket.py:86:
 
TypeError

 
1 failed in 0.36 seconds 
=
Task was destroyed but it is pending!
task: 
 
wait_for=()]> cb=[Future.set_result()]>



P.S. I have a couple more problems with testing this particular project 
related to channels. For example I tried ignoring this disconnect problem, 
this test passed with 99% coverage, but when I run the whole test suite it 
breaks and I figured out what other tests break this one, but not sure why. 
Would you mind looking at this too? If yes, should I create a new thread or 
continue in this one?


On Thursday, February 8, 2018 at 4:07:38 AM UTC+6, Andrew Godwin wrote:
>
> I'm not going to address the mocking, as there's subtle details there 
> (e.g. you mocked group_name as a non-property, I think), but look at the 
> main issue.
>
> Can you make your code print out what _is_ in `self.scope`? url_route 
> should definitely be in there, but I am curious what it looks like if it is 
> not.
>
> Andrew
>
> On Wed, Feb 7, 2018 at 12:16 PM, Azamat Galimzhanov <
> aza...@galimzhanov.com > wrote:
>
>> Hello,
>>
>> I'm setting up an auctions application using channels and websockets. 
>> When I'm running the server the code works just fine, troubles arise when 
>> I'm trying to test my app.
>>
>> asgiref==2.1.3
>> daphne==2.0.2
>> Django==2.0.2
>> channels==2.0.1
>> channels-redis==2.0.2
>> pytest==3.4.0
>> pytest-asyncio==0.8.0
>>
>> a bunch of other stuff, but I think that's it for relevant libraries.
>>
>> Here is my consumer:
>>
>> class AuctionConsumer(WebsocketConsumer):
>> @property
>> @lru_cache(maxsize=None)
>> def group_name(self):
>> auction_id = 

Re: Testing Channels 2.0 consumers - problem with routing

2018-02-07 Thread Andrew Godwin
I'm not going to address the mocking, as there's subtle details there (e.g.
you mocked group_name as a non-property, I think), but look at the main
issue.

Can you make your code print out what _is_ in `self.scope`? url_route
should definitely be in there, but I am curious what it looks like if it is
not.

Andrew

On Wed, Feb 7, 2018 at 12:16 PM, Azamat Galimzhanov 
wrote:

> Hello,
>
> I'm setting up an auctions application using channels and websockets. When
> I'm running the server the code works just fine, troubles arise when I'm
> trying to test my app.
>
> asgiref==2.1.3
> daphne==2.0.2
> Django==2.0.2
> channels==2.0.1
> channels-redis==2.0.2
> pytest==3.4.0
> pytest-asyncio==0.8.0
>
> a bunch of other stuff, but I think that's it for relevant libraries.
>
> Here is my consumer:
>
> class AuctionConsumer(WebsocketConsumer):
> @property
> @lru_cache(maxsize=None)
> def group_name(self):
> auction_id = self.scope['url_route']['kwargs']['auction_id']
> return 'auction_{}'.format(auction_id)
>
> def connect(self):
> AsyncToSync(self.channel_layer.group_add)(self.group_name, 
> self.channel_name)
> self.accept()
>
>
> Here is my routing:
>
> application = ProtocolTypeRouter({
> 'websocket': URLRouter([
> path("auctions//", AuctionConsumer),
> ]),
> })
>
>
> And here is my test:
>
>
> @pytest.mark.asyncio
> async def test_auction_consumer(mocker):
> communicator = WebsocketCommunicator(AuctionConsumer, 'auctions/1/')
> connected, subprotocol = await communicator.connect()
> assert connected
> # Test sending text
> await communicator.send_to(text_data='1')
> response = await communicator.receive_from()
> assert response == '1'
> # Close
> await communicator.disconnect()
>
>
>
> I'm running into the following problem;
>
> @property
> @lru_cache(maxsize=None)
> def group_name(self):
> >   auction_id = self.scope['url_route']['kwargs']['auction_id']
> E   KeyError: 'url_route'
>
> I tried mocking at the top of my test:
>
> group_name = mocker.patch('auctions.consumers.AuctionConsumer.group_name')
> group_name.return_value = 'auction'
>
>
> But then I run into:
>
> def valid_group_name(self, name):
> if self.match_type_and_length(name):
> if bool(self.group_name_regex.match(name)):
> return True
> raise TypeError(
> "Group name must be a valid unicode string containing only
> ASCII " +
> >   "alphanumerics, hyphens, or periods."
> )
> E   TypeError: Group name must be a valid unicode string containing
> only ASCII alphanumerics, hyphens, or periods.
>
>
> I also tried:
>
> scope = mocker.patch('auctions.consumers.AuctionConsumer.scope')
> scope.return_value = {'url_route': {}}
>
>
> But that got me:
>
> if not self.create and original is DEFAULT:
> raise AttributeError(
> >   "%s does not have the attribute %r" % (target, name)
> )
> E   AttributeError: 
> does not have the attribute 'scope'
>
>
> At this point I'm out of ideas. Anything I should try?
>
> 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 https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/528e93c5-dfb1-4cc1-a599-b99404c59533%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/CAFwN1uoZ875%3DO%3DPdurHw%3DtrHR960Pm1KnEjue0EKCzx%2BAnWdMw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing Channels database data missing in Consumer

2018-02-07 Thread Andrew Godwin
Interesting. I did note that you called ORM methods in an async context,
which is not how you are supposed to do it, but I also believe that should
work. Maybe try splitting the ORM methods into a separate function and
awaiting it using SyncToAsync?

As for the staticfiles in live test case problem, I have opened a ticket
for that: https://github.com/django/channels/issues/880

Andrew

On Wed, Feb 7, 2018 at 9:51 AM, Daniel Gilge  wrote:

> Hi Andrew,
>
> thanks for your reply.
>
> This test is passing (using the same packages):
>
> def test_fixture(db_with_segment, admin_client):
> assert models.MyModel.objects.count() == 1
> response = admin_client.get('/api/my_model/list/')
> assert len(response.json()['results']) == 1
>
> I tried to write a simpler async test with asyncio.wait but I didn't
> complete it so far.
>
> I thought to just write ChannelsLiveServerTestCase tests but I couldn't
> manage to serve static files there. (Both, setting static_handler =
> StaticFilesHandler – what StaticLiveServerTestCase does – and running
> collectstatic didn't work.)
>
> Finally I ran my development server and did some tests in the browser
> console. There it works. I'll continue coding using this technique to
> "test" my code and try to find a solution for the other (real) tests as I
> have time.
>
> Am Mittwoch, 7. Februar 2018 04:31:14 UTC+1 schrieb Andrew Godwin:
>>
>> I'm not quite sure either. Does the test setup work if you are not in
>> async mode?
>>
>> Andrew
>>
>> On Tue, Feb 6, 2018 at 9:45 AM, Daniel Gilge  wrote:
>>
>>> Hi,
>>>
>>> this question is related to Channels 2.0, Django 2.0, pytest 3.4,
>>> pytest-django 3.1 and pytest-asyncio 0.8.
>>>
>>> I created a pytest:
>>>
>>> @pytest.fixture
>>> def db_with_obj(db):
>>> factories.MyModelFactory()
>>>
>>> @pytest.mark.asyncio
>>> async def test_something(db_with_obj):
>>> print(models.MyModelFactory.objects.all())
>>> obj = models.MyModelFactory.objects.first()
>>> communicator = WebsocketCommunicator(MyConsumer, 'ws/')
>>> connected, subprotocol = await communicator.connect()
>>> assert connected
>>> await communicator.send_to(text_data=json.dumps({
>>> 'id': obj.pk,
>>> 'content': 'my content',
>>> }))
>>> response = await communicator.receive_from()
>>> assert response == 'my content'
>>> await communicator.disconnect()
>>>
>>> print gives me ]>
>>>
>>> Here my Consumer code:
>>>
>>> class MyConsumer(WebsocketConsumer):
>>> def receive(self, text_data=None, bytes_data=None):
>>> print(models.MyModel.objects.all())
>>> # ...
>>>
>>> print gives me 
>>>
>>> I don't know what I'm doing wrong. I didn't use both, pytest and Python
>>> async code, before. Therefore I don't know where to look for the solution,
>>> though I think it's easy to solve. Any hint appreciated.
>>>
>>> Thanks :)
>>>
>>> --
>>> 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 https://groups.google.com/group/django-users.
>>> To view this discussion on the web visit https://groups.google.com/d/ms
>>> gid/django-users/7e5f63f4-789c-413e-a8d2-fcf8ea62a2cb%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/464c465b-8b24-4061-977d-a44b4868fc84%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/CAFwN1ur8xAgTd21ntmV6dyYD6eTTLW3HWghTHLVT_OJHr0UJNA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing Channels database data missing in Consumer

2018-02-07 Thread Daniel Gilge
Hi Andrew,

thanks for your reply.

This test is passing (using the same packages):

def test_fixture(db_with_segment, admin_client):
assert models.MyModel.objects.count() == 1
response = admin_client.get('/api/my_model/list/')
assert len(response.json()['results']) == 1

I tried to write a simpler async test with asyncio.wait but I didn't 
complete it so far.

I thought to just write ChannelsLiveServerTestCase tests but I couldn't 
manage to serve static files there. (Both, setting static_handler = 
StaticFilesHandler – what StaticLiveServerTestCase does – and running 
collectstatic didn't work.)

Finally I ran my development server and did some tests in the browser 
console. There it works. I'll continue coding using this technique to 
"test" my code and try to find a solution for the other (real) tests as I 
have time.

Am Mittwoch, 7. Februar 2018 04:31:14 UTC+1 schrieb Andrew Godwin:
>
> I'm not quite sure either. Does the test setup work if you are not in 
> async mode?
>
> Andrew
>
> On Tue, Feb 6, 2018 at 9:45 AM, Daniel Gilge  > wrote:
>
>> Hi,
>>
>> this question is related to Channels 2.0, Django 2.0, pytest 3.4, 
>> pytest-django 3.1 and pytest-asyncio 0.8.
>>
>> I created a pytest:
>>
>> @pytest.fixture
>> def db_with_obj(db):
>> factories.MyModelFactory()
>>
>> @pytest.mark.asyncio
>> async def test_something(db_with_obj):
>> print(models.MyModelFactory.objects.all())
>> obj = models.MyModelFactory.objects.first()
>> communicator = WebsocketCommunicator(MyConsumer, 'ws/')
>> connected, subprotocol = await communicator.connect()
>> assert connected
>> await communicator.send_to(text_data=json.dumps({
>> 'id': obj.pk,
>> 'content': 'my content',
>> }))
>> response = await communicator.receive_from()
>> assert response == 'my content'
>> await communicator.disconnect()
>>
>> print gives me ]>
>>
>> Here my Consumer code:
>>
>> class MyConsumer(WebsocketConsumer):
>> def receive(self, text_data=None, bytes_data=None):
>> print(models.MyModel.objects.all())
>> # ...
>>
>> print gives me 
>>
>> I don't know what I'm doing wrong. I didn't use both, pytest and Python 
>> async code, before. Therefore I don't know where to look for the solution, 
>> though I think it's easy to solve. Any hint appreciated.
>>
>> Thanks :)
>>
>> -- 
>> 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 https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/7e5f63f4-789c-413e-a8d2-fcf8ea62a2cb%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/464c465b-8b24-4061-977d-a44b4868fc84%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing Channels database data missing in Consumer

2018-02-06 Thread Andrew Godwin
I'm not quite sure either. Does the test setup work if you are not in async
mode?

Andrew

On Tue, Feb 6, 2018 at 9:45 AM, Daniel Gilge  wrote:

> Hi,
>
> this question is related to Channels 2.0, Django 2.0, pytest 3.4,
> pytest-django 3.1 and pytest-asyncio 0.8.
>
> I created a pytest:
>
> @pytest.fixture
> def db_with_obj(db):
> factories.MyModelFactory()
>
> @pytest.mark.asyncio
> async def test_something(db_with_obj):
> print(models.MyModelFactory.objects.all())
> obj = models.MyModelFactory.objects.first()
> communicator = WebsocketCommunicator(MyConsumer, 'ws/')
> connected, subprotocol = await communicator.connect()
> assert connected
> await communicator.send_to(text_data=json.dumps({
> 'id': obj.pk,
> 'content': 'my content',
> }))
> response = await communicator.receive_from()
> assert response == 'my content'
> await communicator.disconnect()
>
> print gives me ]>
>
> Here my Consumer code:
>
> class MyConsumer(WebsocketConsumer):
> def receive(self, text_data=None, bytes_data=None):
> print(models.MyModel.objects.all())
> # ...
>
> print gives me 
>
> I don't know what I'm doing wrong. I didn't use both, pytest and Python
> async code, before. Therefore I don't know where to look for the solution,
> though I think it's easy to solve. Any hint appreciated.
>
> Thanks :)
>
> --
> 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/7e5f63f4-789c-413e-a8d2-fcf8ea62a2cb%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/CAFwN1uovKqRZJzWjd7CwWxQPkq1vCEMRTV-F1kFGtE8YDyecHw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing

2018-01-14 Thread yingi keme
Yes it does post

Yingi Kem

> On 14 Jan 2018, at 10:07 PM, Rich Shepard  wrote:
> 
>  I've not received messages from this mail list since last summer. I now
> have a need to communicate with others and learned that I'm still subscribed
> so I want to learn if this message posts and is sent back to me by the MLM.
> 
> Rich
> 
> -- 
> 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/alpine.LNX.2.20.1801141304320.5312%40salmo.appl-ecosys.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/62E14FBA-DCE0-4A25-8C94-BAA79D4D912C%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing file upload via a form?

2017-09-10 Thread Derek
Thanks Melvyn

Yes, over time I have come to learn the need for fat models and  Useful
Managers, plus having logic not embedded in the views (especially for
processing of data arising from a form).  So views are mostly "handlers" to
ensure that the forms are presented, the data is retrieved and passed on to
a processing method, and then the flow redirected to the right URL.

I have got hung up on the "mechanics" of form testing instead of seeing
that they only play a small role in the project.  I will however, persist
until I get the grammar correct.

Derek



On 3 September 2017 at 16:14, Melvyn Sopacua  wrote:

> It certainly isn't trivial.
>
> First and foremost, write fat models and Managers, but lean views.
>
> Rather then putting complex queries in views, I have a strong bias
> to writing manager methods (or QuerySet methods, if I feel it's
> reusable in more then one Manager - see Manager.from_queryset [1]).
>
> Further more, I tend to use the setup described here [2] also for
> projects. But for the `test_settings.py` I use:
>
> from project_app.settings import *
>
> INSTALLED_APPS += ['tests.apps.TestsConfig']
>
> This makes it trivial to test fields on their own, by creating models
> that only exist in the test environment.
>
> Normally, you want to test all components on their own, but with
> forms being so tightly coupled to and influenced by views and urls,
> it is non-trivial to predict what affects your form and thus test for it.
> It's easy to get 100% coverage on your form and still know nothing,
> because the input variations are important.
> Yes, it's possible to do with different initialization, but you're going
> to test your views anyway, so why not use the test client, as your
> views eventually determine what happens with them and are pretty
> much the only way to use them. On top of that, you're testing your
> urls for free.
>
> So in general, a Django test suite consists of:
> * model tests
> * view tests using django.test.Client
> * template tests [3]
> * command tests [4]
> * utility tests
>
> Hope this helps,
>
> [1] https://docs.djangoproject.com/en/1.11/topics/db/
> managers/#creating-a-manager-with-queryset-methods
> [2] https://docs.djangoproject.com/en/1.11/topics/testing/
> advanced/#testing-reusable-applications
> [3] shameless plug warning:
> http://django-xtc.readthedocs.io/en/latest/index.html
> [4] https://docs.djangoproject.com/en/1.11/ref/django-admin/#
> django.core.management.call_command
>
> On Sun, Sep 3, 2017 at 10:05 AM, Derek  wrote:
> > I have been looking for a decent guide that covers testing in a solid,
> > thorough way - there are lots of fragmented pieces that cover
> > bits-and-pieces of what is needed for tests but not all the cases with a
> > start-to-end comprehensive approach for everything ("Obey the Testing
> Goat"
> > comes closest). I need to cover cases for the admin as well - with
> actions
> > and intermediate forms, some with file uploads. In those case, I assume
> (?)
> > that the action logic is equivalent to a view.
> >
> > The Django docs show examples as well but I have not see where they cover
> > everything.
> >
> > This may all seem like trivial knowledge to people who have already done
> all
> > this, but I struggle to see the full picture of what a whole test suite
> > should look like, and what the details of all the tests would be.
> >
> >
> > On 3 September 2017 at 09:07, James Schneider 
> > wrote:
> >>
> >>
> >>
> >> On Sep 1, 2017 3:00 PM, "Derek"  wrote:
> >>
> >> Thanks Melvyn
> >>
> >> I already have tests for the processing of data when it has been
> uploaded
> >> - which is actually the critical issue for the application.  The "view"
> is
> >> just really a thin wrapper around the two steps : form display & upload
> and
> >> then the file processing itself : and those are the parts I need tests
> for.
> >>
> >>
> >> I'd have to agree with Melvin. You should be testing your view code as
> >> well, which would incorporate the tests for the form class. If the view
> is
> >> broken out interacts badly with the form for whatever reason, the fact
> that
> >> the form works on it's own is irrelevant. Plus it isn't that hard to
> add in.
> >>
> >> I would test the view even if it is boiler plate code shared by all of
> >> your forms, because you need to be certain that the combination of the
> view
> >> and form in question work together.
> >>
> >> -James
> >>
> >> --
> >> You received this message because you are subscribed to a topic in the
> >> Google Groups "Django users" group.
> >> To unsubscribe from this topic, visit
> >> https://groups.google.com/d/topic/django-users/GUStj-3rzD8/unsubscribe.
> >> To unsubscribe from this group and all its topics, 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 

Re: Testing file upload via a form?

2017-09-03 Thread Melvyn Sopacua
It certainly isn't trivial.

First and foremost, write fat models and Managers, but lean views.

Rather then putting complex queries in views, I have a strong bias
to writing manager methods (or QuerySet methods, if I feel it's
reusable in more then one Manager - see Manager.from_queryset [1]).

Further more, I tend to use the setup described here [2] also for
projects. But for the `test_settings.py` I use:

from project_app.settings import *

INSTALLED_APPS += ['tests.apps.TestsConfig']

This makes it trivial to test fields on their own, by creating models
that only exist in the test environment.

Normally, you want to test all components on their own, but with
forms being so tightly coupled to and influenced by views and urls,
it is non-trivial to predict what affects your form and thus test for it.
It's easy to get 100% coverage on your form and still know nothing,
because the input variations are important.
Yes, it's possible to do with different initialization, but you're going
to test your views anyway, so why not use the test client, as your
views eventually determine what happens with them and are pretty
much the only way to use them. On top of that, you're testing your
urls for free.

So in general, a Django test suite consists of:
* model tests
* view tests using django.test.Client
* template tests [3]
* command tests [4]
* utility tests

Hope this helps,

[1] 
https://docs.djangoproject.com/en/1.11/topics/db/managers/#creating-a-manager-with-queryset-methods
[2] 
https://docs.djangoproject.com/en/1.11/topics/testing/advanced/#testing-reusable-applications
[3] shameless plug warning:
http://django-xtc.readthedocs.io/en/latest/index.html
[4] 
https://docs.djangoproject.com/en/1.11/ref/django-admin/#django.core.management.call_command

On Sun, Sep 3, 2017 at 10:05 AM, Derek  wrote:
> I have been looking for a decent guide that covers testing in a solid,
> thorough way - there are lots of fragmented pieces that cover
> bits-and-pieces of what is needed for tests but not all the cases with a
> start-to-end comprehensive approach for everything ("Obey the Testing Goat"
> comes closest). I need to cover cases for the admin as well - with actions
> and intermediate forms, some with file uploads. In those case, I assume (?)
> that the action logic is equivalent to a view.
>
> The Django docs show examples as well but I have not see where they cover
> everything.
>
> This may all seem like trivial knowledge to people who have already done all
> this, but I struggle to see the full picture of what a whole test suite
> should look like, and what the details of all the tests would be.
>
>
> On 3 September 2017 at 09:07, James Schneider 
> wrote:
>>
>>
>>
>> On Sep 1, 2017 3:00 PM, "Derek"  wrote:
>>
>> Thanks Melvyn
>>
>> I already have tests for the processing of data when it has been uploaded
>> - which is actually the critical issue for the application.  The "view" is
>> just really a thin wrapper around the two steps : form display & upload and
>> then the file processing itself : and those are the parts I need tests for.
>>
>>
>> I'd have to agree with Melvin. You should be testing your view code as
>> well, which would incorporate the tests for the form class. If the view is
>> broken out interacts badly with the form for whatever reason, the fact that
>> the form works on it's own is irrelevant. Plus it isn't that hard to add in.
>>
>> I would test the view even if it is boiler plate code shared by all of
>> your forms, because you need to be certain that the combination of the view
>> and form in question work together.
>>
>> -James
>>
>> --
>> You received this message because you are subscribed to a topic in the
>> Google Groups "Django users" group.
>> To unsubscribe from this topic, visit
>> https://groups.google.com/d/topic/django-users/GUStj-3rzD8/unsubscribe.
>> To unsubscribe from this group and all its topics, 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%2BciUgbWkGFVrqBWKAYdifP%2BjTchZwHR0-GfPKGcTjP%3DBjfA%40mail.gmail.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/CAF1Wu3MqT1V85StnBg8D_eqrcjH%2BebjvDW41xg_V1t%3D9%3DeUk-Q%40mail.gmail.com.
>
> For more options, visit 

Re: Testing file upload via a form?

2017-09-03 Thread Derek
I have been looking for a decent guide that covers testing in a solid,
thorough way - there are lots of fragmented pieces that cover
bits-and-pieces of what is needed for tests but not all the cases with a
start-to-end comprehensive approach for everything ("Obey the Testing Goat"
comes closest). I need to cover cases for the admin as well - with actions
and intermediate forms, some with file uploads. In those case, I assume (?)
that the action logic is equivalent to a view.

The Django docs show examples as well but I have not see where they cover
everything.

This may all seem like trivial knowledge to people who have already done
all this, but I struggle to see the full picture of what a whole test suite
should look like, and what the details of all the tests would be.


On 3 September 2017 at 09:07, James Schneider 
wrote:

>
>
> On Sep 1, 2017 3:00 PM, "Derek"  wrote:
>
> Thanks Melvyn
>
> I already have tests for the processing of data when it has been uploaded
> - which is actually the critical issue for the application.  The "view" is
> just really a thin wrapper around the two steps : form display & upload and
> then the file processing itself : and those are the parts I need tests for.
>
>
> I'd have to agree with Melvin. You should be testing your view code as
> well, which would incorporate the tests for the form class. If the view is
> broken out interacts badly with the form for whatever reason, the fact that
> the form works on it's own is irrelevant. Plus it isn't that hard to add
> in.
>
> I would test the view even if it is boiler plate code shared by all of
> your forms, because you need to be certain that the combination of the view
> and form in question work together.
>
> -James
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/
> topic/django-users/GUStj-3rzD8/unsubscribe.
> To unsubscribe from this group and all its topics, 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%2BciUgbWkGFVrqBWKAYdifP%
> 2BjTchZwHR0-GfPKGcTjP%3DBjfA%40mail.gmail.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/CAF1Wu3MqT1V85StnBg8D_eqrcjH%2BebjvDW41xg_V1t%3D9%3DeUk-Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing file upload via a form?

2017-09-03 Thread James Schneider
On Sep 1, 2017 3:00 PM, "Derek"  wrote:

Thanks Melvyn

I already have tests for the processing of data when it has been uploaded -
which is actually the critical issue for the application.  The "view" is
just really a thin wrapper around the two steps : form display & upload and
then the file processing itself : and those are the parts I need tests for.


I'd have to agree with Melvin. You should be testing your view code as
well, which would incorporate the tests for the form class. If the view is
broken out interacts badly with the form for whatever reason, the fact that
the form works on it's own is irrelevant. Plus it isn't that hard to add
in.

I would test the view even if it is boiler plate code shared by all of your
forms, because you need to be certain that the combination of the view and
form in question work together.

-James

-- 
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%2BciUgbWkGFVrqBWKAYdifP%2BjTchZwHR0-GfPKGcTjP%3DBjfA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing file upload via a form?

2017-09-01 Thread Derek
Thanks Melvyn

I already have tests for the processing of data when it has been uploaded -
which is actually the critical issue for the application.  The "view" is
just really a thin wrapper around the two steps : form display & upload and
then the file processing itself : and those are the parts I need tests for.


On 1 September 2017 at 17:12, Melvyn Sopacua  wrote:

> You're not using the test **Client** at all. You're testing the value
> of a form.Form instance.
>
> The difference is that the test client constructs an actual request,
> using the known URLs. So you'd need a view and url as well.
> But these can exist only in the test and to be honest, especially
> with uploads, I'm more interested in the upload working when used
> in a view, then whether the form works in an environment it's never
> going to be used in.
>
> That said, James is right on the money with the payload. It doesn't
> however tell you file uploads are going to work, only that a correctly
> bound file passes validation.
>
>
> On Fri, Sep 1, 2017 at 9:07 AM, Derek  wrote:
> > Thanks Melvyn
> >
> > I thought my code did follow that approach - but it does not seem to
> work.
> > So either I have not understood the docs (in which case, a point to the
> > specific item is what I need) or there is some other factor at work.
> >
> > On 31 August 2017 at 16:47, Melvyn Sopacua 
> wrote:
> >>
> >> In the documentation of the test client it is all spelled out how to
> test
> >> file uploads.
> >>
> >> On Tue, Aug 29, 2017 at 8:48 PM, Derek  wrote:
> >>>
> >>> (Python 3.5 and Django 1.10)
> >>>
> >>> I am trying to test a Django form that enables a required file upload.
> >>>
> >>> The form is very simple and includes a field that looks like:
> >>>
> >>> upload_file = forms.FileField()
> >>>
> >>> The corresponding test to try and check the upload:
> >>>
> >>> def test_form_validation_with_file(self):
> >>> fake_file = ContentFile(b'''Some file content''')
> >>> fake_file.name = 'fake.xls'
> >>> suf_file = SimpleUploadedFile('suf.xls', b'''this is text''')
> >>> data = {
> >>> 'upload_file': suf_file,
> >>> }
> >>> form = forms.RequestForm(data=data)
> >>> self.assertTrue(form.is_valid())
> >>>
> >>> The form validation fails i.e. it does not seem to recognise that file
> >>> data has been suppplied.
> >>>
> >>> I have also tried with the  "fake_file" for the data but without
> success.
> >>>
> >>> Any help or pointers appreciated.
> >>>
> >>> 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 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/
> CAF1Wu3OTCbnw4o749YUz-Pa1-Uo9jkGkd1KybB5rSLnp3eAMDQ%40mail.gmail.com.
> >>> For more options, visit https://groups.google.com/d/optout.
> >>
> >>
> >>
> >>
> >> --
> >> Melvyn Sopacua
> >>
> >> --
> >> You received this message because you are subscribed to a topic in the
> >> Google Groups "Django users" group.
> >> To unsubscribe from this topic, visit
> >> https://groups.google.com/d/topic/django-users/GUStj-3rzD8/unsubscribe.
> >> To unsubscribe from this group and all its topics, 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%
> 2Bgw1GVt-pwLwdTx_0m2nj-uy0A%3DBQh8L1aeFNnraMCAy%3DP-iw%40mail.gmail.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/CAF1Wu3NR3Wqv56-
> i3xOo6QGrGU1Et5z3Kg-PM%2BGbBB6j5b2ZGw%40mail.gmail.com.
> >
> > For more options, visit https://groups.google.com/d/optout.
>
>
>
> --
> Melvyn Sopacua
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/
> topic/django-users/GUStj-3rzD8/unsubscribe.
> To unsubscribe from this group and all its 

Re: Testing file upload via a form?

2017-09-01 Thread Melvyn Sopacua
You're not using the test **Client** at all. You're testing the value
of a form.Form instance.

The difference is that the test client constructs an actual request,
using the known URLs. So you'd need a view and url as well.
But these can exist only in the test and to be honest, especially
with uploads, I'm more interested in the upload working when used
in a view, then whether the form works in an environment it's never
going to be used in.

That said, James is right on the money with the payload. It doesn't
however tell you file uploads are going to work, only that a correctly
bound file passes validation.


On Fri, Sep 1, 2017 at 9:07 AM, Derek  wrote:
> Thanks Melvyn
>
> I thought my code did follow that approach - but it does not seem to work.
> So either I have not understood the docs (in which case, a point to the
> specific item is what I need) or there is some other factor at work.
>
> On 31 August 2017 at 16:47, Melvyn Sopacua  wrote:
>>
>> In the documentation of the test client it is all spelled out how to test
>> file uploads.
>>
>> On Tue, Aug 29, 2017 at 8:48 PM, Derek  wrote:
>>>
>>> (Python 3.5 and Django 1.10)
>>>
>>> I am trying to test a Django form that enables a required file upload.
>>>
>>> The form is very simple and includes a field that looks like:
>>>
>>> upload_file = forms.FileField()
>>>
>>> The corresponding test to try and check the upload:
>>>
>>> def test_form_validation_with_file(self):
>>> fake_file = ContentFile(b'''Some file content''')
>>> fake_file.name = 'fake.xls'
>>> suf_file = SimpleUploadedFile('suf.xls', b'''this is text''')
>>> data = {
>>> 'upload_file': suf_file,
>>> }
>>> form = forms.RequestForm(data=data)
>>> self.assertTrue(form.is_valid())
>>>
>>> The form validation fails i.e. it does not seem to recognise that file
>>> data has been suppplied.
>>>
>>> I have also tried with the  "fake_file" for the data but without success.
>>>
>>> Any help or pointers appreciated.
>>>
>>> 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 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/CAF1Wu3OTCbnw4o749YUz-Pa1-Uo9jkGkd1KybB5rSLnp3eAMDQ%40mail.gmail.com.
>>> For more options, visit https://groups.google.com/d/optout.
>>
>>
>>
>>
>> --
>> Melvyn Sopacua
>>
>> --
>> You received this message because you are subscribed to a topic in the
>> Google Groups "Django users" group.
>> To unsubscribe from this topic, visit
>> https://groups.google.com/d/topic/django-users/GUStj-3rzD8/unsubscribe.
>> To unsubscribe from this group and all its topics, 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%2Bgw1GVt-pwLwdTx_0m2nj-uy0A%3DBQh8L1aeFNnraMCAy%3DP-iw%40mail.gmail.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/CAF1Wu3NR3Wqv56-i3xOo6QGrGU1Et5z3Kg-PM%2BGbBB6j5b2ZGw%40mail.gmail.com.
>
> For more options, visit https://groups.google.com/d/optout.



-- 
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/CA%2Bgw1GVCX8%2B%3DpLgtxq0ZiqSRohbigHTYsTCB3VtDLhSyj3b_%2BQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing file upload via a form?

2017-09-01 Thread Derek
Thanks James, I will try that.

On 1 September 2017 at 09:27, James Schneider 
wrote:

>
>
> On Aug 29, 2017 11:49 AM, "Derek"  wrote:
>
> (Python 3.5 and Django 1.10)
>
> I am trying to test a Django form that enables a required file upload.
>
> The form is very simple and includes a field that looks like:
>
> upload_file = forms.FileField()
>
> The corresponding test to try and check the upload:
>
> def test_form_validation_with_file(self):
> fake_file = ContentFile(b'''Some file content''')
> fake_file.name = 'fake.xls'
> suf_file = SimpleUploadedFile('suf.xls', b'''this is text''')
> data = {
> 'upload_file': suf_file,
> }
> form = forms.RequestForm(data=data)
> self.assertTrue(form.is_valid())
>
> The form validation fails i.e. it does not seem to recognise that file
> data has been suppplied.
>
> I have also tried with the  "fake_file" for the data but without success.
>
> Any help or pointers appreciated.
>
>
> It does not appear that you are binding the file to the form correctly.
> Django forms use a separate argument to the form class for file content. It
> is not part of the form 'data'.
>
> https://docs.djangoproject.com/en/1.11/ref/forms/api/#
> binding-uploaded-files-to-a-form
>
> -James
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/
> topic/django-users/GUStj-3rzD8/unsubscribe.
> To unsubscribe from this group and all its topics, 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%2BciWEKPqL7%3DLpVpREaZExSediHf6nqa5mrbWoyn
> fi8jYy5g%40mail.gmail.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/CAF1Wu3Md5D%2B-fg%2BQZE5DEHyyqV0qGkiq7i%3DUHiv1QGi86oNX0Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing file upload via a form?

2017-09-01 Thread James Schneider
On Aug 29, 2017 11:49 AM, "Derek"  wrote:

(Python 3.5 and Django 1.10)

I am trying to test a Django form that enables a required file upload.

The form is very simple and includes a field that looks like:

upload_file = forms.FileField()

The corresponding test to try and check the upload:

def test_form_validation_with_file(self):
fake_file = ContentFile(b'''Some file content''')
fake_file.name = 'fake.xls'
suf_file = SimpleUploadedFile('suf.xls', b'''this is text''')
data = {
'upload_file': suf_file,
}
form = forms.RequestForm(data=data)
self.assertTrue(form.is_valid())

The form validation fails i.e. it does not seem to recognise that file data
has been suppplied.

I have also tried with the  "fake_file" for the data but without success.

Any help or pointers appreciated.


It does not appear that you are binding the file to the form correctly.
Django forms use a separate argument to the form class for file content. It
is not part of the form 'data'.

https://docs.djangoproject.com/en/1.11/ref/forms/api/#binding-uploaded-files-to-a-form

-James

-- 
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%2BciWEKPqL7%3DLpVpREaZExSediHf6nqa5mrbWoynfi8jYy5g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing file upload via a form?

2017-09-01 Thread Derek
Thanks Melvyn

I thought my code did follow that approach - but it does not seem to work.
So either I have not understood the docs (in which case, a point to the
specific item is what I need) or there is some other factor at work.

On 31 August 2017 at 16:47, Melvyn Sopacua  wrote:

> ​In the documentation of the test client
> 
>  it
> is all spelled out how to test file uploads.
> ​
> ​
>
> On Tue, Aug 29, 2017 at 8:48 PM, Derek  wrote:
>
>> (Python 3.5 and Django 1.10)
>>
>> I am trying to test a Django form that enables a required file upload.
>>
>> The form is very simple and includes a field that looks like:
>>
>> upload_file = forms.FileField()
>>
>> The corresponding test to try and check the upload:
>>
>> def test_form_validation_with_file(self):
>> fake_file = ContentFile(b'''Some file content''')
>> fake_file.name = 'fake.xls'
>> suf_file = SimpleUploadedFile('suf.xls', b'''this is text''')
>> data = {
>> 'upload_file': suf_file,
>> }
>> form = forms.RequestForm(data=data)
>> self.assertTrue(form.is_valid())
>>
>> The form validation fails i.e. it does not seem to recognise that file
>> data has been suppplied.
>>
>> I have also tried with the  "fake_file" for the data but without success.
>>
>> Any help or pointers appreciated.
>>
>> 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 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/ms
>> gid/django-users/CAF1Wu3OTCbnw4o749YUz-Pa1-Uo9jkGkd1KybB5rSL
>> np3eAMDQ%40mail.gmail.com
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
>
> --
> Melvyn Sopacua
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/
> topic/django-users/GUStj-3rzD8/unsubscribe.
> To unsubscribe from this group and all its topics, 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%2Bgw1GVt-pwLwdTx_0m2nj-uy0A%
> 3DBQh8L1aeFNnraMCAy%3DP-iw%40mail.gmail.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/CAF1Wu3NR3Wqv56-i3xOo6QGrGU1Et5z3Kg-PM%2BGbBB6j5b2ZGw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing file upload via a form?

2017-08-31 Thread Melvyn Sopacua
​In the documentation of the test client

it
is all spelled out how to test file uploads.
​
​

On Tue, Aug 29, 2017 at 8:48 PM, Derek  wrote:

> (Python 3.5 and Django 1.10)
>
> I am trying to test a Django form that enables a required file upload.
>
> The form is very simple and includes a field that looks like:
>
> upload_file = forms.FileField()
>
> The corresponding test to try and check the upload:
>
> def test_form_validation_with_file(self):
> fake_file = ContentFile(b'''Some file content''')
> fake_file.name = 'fake.xls'
> suf_file = SimpleUploadedFile('suf.xls', b'''this is text''')
> data = {
> 'upload_file': suf_file,
> }
> form = forms.RequestForm(data=data)
> self.assertTrue(form.is_valid())
>
> The form validation fails i.e. it does not seem to recognise that file
> data has been suppplied.
>
> I have also tried with the  "fake_file" for the data but without success.
>
> Any help or pointers appreciated.
>
> 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 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/CAF1Wu3OTCbnw4o749YUz-Pa1-Uo9jkGkd1KybB5rSLnp3eAMDQ%
> 40mail.gmail.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 
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/CA%2Bgw1GVt-pwLwdTx_0m2nj-uy0A%3DBQh8L1aeFNnraMCAy%3DP-iw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing in django

2017-05-29 Thread Marlysson Silva
If you are using the sqlite database to dummy test , you can in a test case 
class submit the post to sign up form ( and store at database ) and in 
other class retrieve the user created previously and performs the login .

Em terça-feira, 23 de maio de 2017 04:07:29 UTC-3, Akash Tomar escreveu:
>
> class SignUpTest(TestCase):
> def test_createAccount(self):
> my_data = {'username': 'akash.tomar107', 'password': 'akashtomar',"email":"
> akash.tomar...@gmail.com ", "confirm_password":"akashtomar", 
> "type_of_user":"1", "first_name":"akash", "last_name":"tomar"}
> response = self.client.post('/signup/', json.dumps(my_data), 
> content_type='application/json')
> self.assertIs(json.loads(response.content)["success"], True)
>
> class LoginTest(TestCase):
> def test_login(self):
> my_data = {'username': 'akash.tomar107', 'password': 'akashtomar'}
> response = self.client.post('/login/', json.dumps(my_data), 
> content_type='application/json')
> # import pdb; pdb.set_trace()
> self.assertIs(json.loads(response.content)["login"], True)
>
>
> I want to be able to use the data created while running SignUpTest in the 
> LoginTest. How do I achieve that? Please help.
>

-- 
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/7bf8b68e-4a3c-475b-a14a-aa8eaadadc41%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing in django

2017-05-23 Thread Antonis Christofides
Hi,

one possibility is this:

class UserTest(TestCase):

def setUp(self):
self.my_data = {...}

def test_create_account(self):
response = self.client.post('/signup/', json.dumps(self.my_data),
content_type='application/json')
self.assertIs(...)

def test_login(self):
...

In some cases this will work, but it might also not work (e.g. if you want to
organize tests differently). I've found Two Scoops' advice invaluable on this
issue: 1) Never use fixtures, 2) DRY does not apply to tests. It's fine to
repeat the same code again and again when testing.

Regards,

A.

Antonis Christofides
http://djangodeployment.com

On 2017-05-23 10:07, Akash Tomar wrote:
> class SignUpTest(TestCase):
> def test_createAccount(self):
> my_data = {'username': 'akash.tomar107', 'password':
> 'akashtomar',"email":"akash.tomar...@gmail.com",
> "confirm_password":"akashtomar", "type_of_user":"1", "first_name":"akash",
> "last_name":"tomar"}
> response = self.client.post('/signup/', json.dumps(my_data),
> content_type='application/json')
> self.assertIs(json.loads(response.content)["success"], True)
>
> class LoginTest(TestCase):
> def test_login(self):
> my_data = {'username': 'akash.tomar107', 'password': 'akashtomar'}
> response = self.client.post('/login/', json.dumps(my_data),
> content_type='application/json')
> # import pdb; pdb.set_trace()
> self.assertIs(json.loads(response.content)["login"], True)
>
>
> I want to be able to use the data created while running SignUpTest in the
> LoginTest. How do I achieve that? Please help.
> -- 
> 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/a3625070-4f46-4c68-b912-888b91e42c82%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/e78d2dd3-3e47-f90c-6ec0-97aab76d551b%40djangodeployment.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing in django

2017-05-23 Thread Александр Христюхин (roboslone)
Perhaps fixtures is what you want: https://code.djangoproject.com/wiki/Fixtures 


> On 23 May 2017, at 10:07, Akash Tomar  wrote:
> 
> class SignUpTest(TestCase):
>   def test_createAccount(self):
>   my_data = {'username': 'akash.tomar107', 'password': 
> 'akashtomar',"email":"akash.tomar...@gmail.com", 
> "confirm_password":"akashtomar", "type_of_user":"1", "first_name":"akash", 
> "last_name":"tomar"}
>   response = self.client.post('/signup/', json.dumps(my_data), 
> content_type='application/json')
>   self.assertIs(json.loads(response.content)["success"], True)
> 
> class LoginTest(TestCase):
>   def test_login(self):
>   my_data = {'username': 'akash.tomar107', 'password': 
> 'akashtomar'}
>   response = self.client.post('/login/', json.dumps(my_data), 
> content_type='application/json')
>   # import pdb; pdb.set_trace()
>   self.assertIs(json.loads(response.content)["login"], True)
> 
> 
> I want to be able to use the data created while running SignUpTest in the 
> LoginTest. How do I achieve that? Please help.
> 
> -- 
> 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/a3625070-4f46-4c68-b912-888b91e42c82%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/938F7C2B-E0BE-4F4B-93DD-81C8652BD7AF%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing client's force_login method doesn't seem to be logging in.

2017-03-26 Thread Quentin Fulsher
Actually I just fixed it, You have to save the model after you set the 
password.

On Sunday, March 26, 2017 at 2:35:08 PM UTC-7, Quentin Fulsher wrote:
>
> I'm trying to write a test case for the viewing permissions on a certain 
> webpage. I'm trying to get the client to force_login as a user to test if 
> they can get the view or not. The issue is that my client doesn't seem to 
> be logged in. No matter who I try to login as (There are a few different 
> types of users to test) I get redirected to the login page. The view is 
> decorated with  login_required so this makes a little bit of sense but I'm 
> still not sure why its happening.
>
> Here's the code for my test case:
>
> class AvailabilityListTestCase(TestCase):
> def setUp(self):
> self.admin = User.objects.create(username='admin', email='
> ad...@sb.com', is_superuser=True, is_staff=True)
> self.admin.set_password('admin')
> self.student = User.objects.create(username='student', email='
> stud...@sb.com')
> self.student.set_password('student')
> self.student2 = User.objects.create(username='student2', email='
> stude...@sb.com')
> self.student2.set_password('student2')
> self.tutor = User.objects.create(username='tutor', email='
> tu...@sb.com')
> self.tutor.set_password('tutor')
> self.tutor2 = User.objects.create(username='tutor2', email='
> tut...@sb.com')
> self.tutor2.set_password('tutor2')
> self.student.tutor = self.tutor
> self.c = Client()
> self.url = '/user/tutor/availabilities/'
>
>
> def test_anon_access(self):
> response = self.c.get(self.url)
> self.assertRedirects(response, 
> '/user/login/?next=/user/tutor/availabilities/')
>
>
> def test_owner_access(self):
> self.c.force_login(self.tutor)
> response = self.c.get(self.url)
> self.assertEqual(200, response.status_code)
>
>
> Here's the view:
>
> @login_required
> def list_availabilities(request, username):
> curr_user = request.user
> if not curr_user.is_staff or curr_user.username != username:
> return HttpResponseForbidden()
> requested_user = get_object_or_404(User.objects.all(), username=
> username)
> requested_user_profile = get_user_profile(requested_user)
> availabilities = requested_user_profile.availability_set.all()
> formatted_list = []
> for availability in availabilities:
> formatted_list.append(
> (
> availability.title,
> # Format meaning: `12h:minute am/pm`
> availability.start_time.strftime("%l:%M %p"),
> availability.end_time.strftime("%l:%M %p"),
> )
> )
> return render(
> request,
> 'appointments/availability_list.html',
> {
> 'tutor_username':username,
> 'formatted_list':formatted_list,
> }
> )
>
>
>
> Thanks!
>

-- 
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/c0244ed1-5fd6-4525-b13e-7b772a69b3ed%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing a Django library

2017-03-23 Thread Josh Crompton
There's no Django community standard of which I'm aware for doing this.

There *is* a standard way to run tests for Python projects which use 
setuptools (which yours should do if you want people to be able to `pip 
install` it) [1].

 I usually do something like this blog post describes [2]. Or, you could 
use this cookie cutter template [3] if you don't want to set it up manually 
yourself. It's probably the closest thing you'll find to a "standard".

[1] http://peak.telecommunity.com/DevCenter/setuptools#test
[2] 
http://joebergantine.com/blog/2015/dec/03/test-reusable-django-application-support-multiple-/
[3] https://github.com/pydanny/cookiecutter-djangopackage

On Tuesday, 21 March 2017 09:38:41 UTC+11, th...@copperleaf.com wrote:
>
> I am working on a Django library (which will be packaged) and want to set 
> up testing for it. Looking at a number of existing Django libraries, here 
> seem to be a number of ways to set up testing, and all of them are 
> different.
>
> Are there any best practices? Is there a guide that specifies how it 
> should be done?
>
> T
>
>

-- 
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/e32424cb-8b12-455e-8f16-f73a850d7c26%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing a Django library

2017-03-22 Thread Jani Tiainen

Hi,

Tox is quite neat test wrapper makes which easy to test code against 
multiple versions of Python and Django.



On 21.03.2017 00:38, th...@copperleaf.com wrote:
I am working on a Django library (which will be packaged) and want to 
set up testing for it. Looking at a number of existing Django 
libraries, here seem to be a number of ways to set up testing, and all 
of them are different.


Are there any best practices? Is there a guide that specifies how it 
should be done?


T

--
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/500f7758-2beb-4248-b316-912df984e57b%40googlegroups.com 
.

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


--
Jani Tiainen

--
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/8a810dab-8edc-a8c3-828c-ef2bcbcf9024%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing a Django library

2017-03-21 Thread Avraham Serour
What are the different approaches you found?

I created a simple minimal project inside the tests folder


On Mar 21, 2017 9:59 PM, "bobhaugen"  wrote:

> Very interesting topic. We will be facing the same problem soon, and will
> hope to learn from your experience. Got a code repository yet?
> We're at https://github.com/django-rea
> If and when we have some good answers, I'll report back here.
>
> --
> 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/abec25d4-6f05-4749-ac12-9d350d5ce8ad%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/CAFWa6tK_6SR7CrpCL4iy7Opt5A0-TzTSxoQ4px%2B7rsrgYNxNBQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing a Django library

2017-03-21 Thread bobhaugen
Very interesting topic. We will be facing the same problem soon, and will 
hope to learn from your experience. Got a code repository yet?
We're at https://github.com/django-rea
If and when we have some good answers, I'll report back here.

-- 
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/abec25d4-6f05-4749-ac12-9d350d5ce8ad%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing a reusable app which uses a database

2016-10-03 Thread Victor Porton
Well, I did it.

On Monday, October 3, 2016 at 10:41:59 PM UTC+3, Victor Porton wrote:
>
> I try to make a reusable app which uses transaction.atomic().
>
> When I run my test.py (below) for my reusable app, I get the below errors.
>
> Is it possible to test this reusable app outside of a Django project?
>
> [[[
> import unittest
> from transaction_utils.transaction import retry
>
>
> class TestRetry(unittest.TestCase):
> @retry
> def my_func(self):
> return 123
>
> def test_passthrough(self):
> self.assertEqual(self.my_func(), 123)
>
> if __name__ == '__main__':
> unittest.main()
> ]]]
>
> [[[
> E
> ==
> ERROR: test_passthrough (__main__.TestRetry)
> --
> Traceback (most recent call last):
>   File "test.py", line 11, in test_passthrough
> self.assertEqual(self.my_func(), 123)
>   File 
> "/home/porton/Projects/transaction_utils/transaction_utils/transaction.py", 
> line 24, in func_wrapper
> with transaction.atomic():
>   File "/usr/lib/python3/dist-packages/django/db/transaction.py", line 
> 152, in __enter__
> connection = get_connection(self.using)
>   File "/usr/lib/python3/dist-packages/django/db/transaction.py", line 21, 
> in get_connection
> return connections[using]
>   File "/usr/lib/python3/dist-packages/django/db/utils.py", line 208, in 
> __getitem__
> self.ensure_defaults(alias)
>   File "/usr/lib/python3/dist-packages/django/db/utils.py", line 176, in 
> ensure_defaults
> conn = self.databases[alias]
>   File "/usr/lib/python3/dist-packages/django/utils/functional.py", line 
> 35, in __get__
> res = instance.__dict__[self.name] = self.func(instance)
>   File "/usr/lib/python3/dist-packages/django/db/utils.py", line 156, in 
> databases
> self._databases = settings.DATABASES
>   File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 53, 
> in __getattr__
> self._setup(name)
>   File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 39, 
> in _setup
> % (desc, ENVIRONMENT_VARIABLE))
> django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, 
> but settings are not configured. You must either define the environment 
> variable DJANGO_SETTINGS_MODULE or call settings.configure() before 
> accessing settings.
>
> --
> Ran 1 test in 0.001s
>
> FAILED (errors=1)
> ]]]
>

-- 
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/287b442f-6a59-44d8-a0c6-414b90416c59%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing a reusable app which uses a database

2016-10-03 Thread Carl Meyer
On 10/03/2016 01:41 PM, Victor Porton wrote:
> I try to make a reusable app which uses transaction.atomic().
> 
> When I run my test.py (below) for my reusable app, I get the below errors.
> 
> Is it possible to test this reusable app outside of a Django project?

It is not possible to test it without setting up Django, no. But you
don't need a full-fledged "project" for this, the bare minimum you need
to do is

import django
from django.conf import settings

settings.configure()  # if you need any settings, pass as a dict
django.setup()

before running your tests.

Carl

-- 
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/0c2f6add-3aab-cb11-981e-3147e203a12a%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Testing if a view have an html element with at least one attribute

2016-08-03 Thread Fred Stluka

  
  
Ludovic,

On my project, we have lots of test cases that do a GET or POST and

then check the returned HTML.  We use the BeautifulSoup HTML 
parser from our Django tests to avoid the types of errors you're 
getting with simple string comparisons.  I'm not sure if there any
pros/cons vs lxml, but it works great for us!

--Fred
  
  
  Fred Stluka -- mailto:f...@bristle.com --
  http://bristle.com/~fred/
  
  Bristle Software, Inc -- http://bristle.com -- Glad to be of
  service!
  
  Open Source: Without walls and fences, we need no Windows or
  Gates.
  
  

On 7/31/16 5:08 PM, Andreas Kuhne
  wrote:


  Jupp, thats about what I meant :-)


Probably the best way, if you don't want to check text.


Regards,


Andréas

  
  2016-07-31 18:01 GMT+02:00 ludovic
coues :
Currently,
  I am using lxml. More dependencies but it's the cleanest
  method I've found currently.
  I use it like that:
  
      from django.test import TestCase
      from lxml import etree
  
      class FormTest(TestCase):
          def test_input(self):
              response = self.client.get('/accounts/login')
              self.assertEqual(response.status_code, 200)
              doc = etree.HTML(response.content)
             
  self.assertEqual(len(doc.findall('.//input[@name="username"]')),
  1)
  

  
  
  2016-07-31 17:46 GMT+02:00 Andreas Kuhne :
  > 2016-07-31 15:59 GMT+02:00 ludovic coues :
  >>
  >> Oh, sorry. A bit of misunderstanding and
  miscommunication on my part.
  >>
  >> The exemple I gave is just a quick way to
  reproduce my problem. The
  >> real test use self.client, reverse, cast
  response.content to a string.
  >> What I gave is a minimal exemple.
  >>
  >> Also, I assumed you talked about comparing
  bit of html element, not
  >> the raw content returned by the view. I'm
  quite uneasy to have the
  >> test failing if a class is added or removed
  from the element. But yes,
  >> your solution work for the current state of
  the application.
  >>
  >> 2016-07-31 14:46 GMT+02:00 Andreas Kuhne :
  >> > 2016-07-31 13:56 GMT+02:00 ludovic coues
  :
  >> >>
  >> >> First, thanks for the suggestion.
  >> >>
  >> >> I just tried that, didn't work.
  >> >> Here is the test file I used:
  >> >>
  >> >>
  >> >>     from django.test import TestCase
  >> >>
  >> >>     class HTMLTestCase(TestCase):
  >> >>
  >> >>         def
  test_input_in_fieldset(self):
  >> >>             fieldset = """
  >> >>         
  >> >>             
  >> >>             
  >> >> maxlength="254" name="username"
  rows="3" type="text" required />
  >> >>         
  >> >>     """
  >> >>           
   self.assertInHTML('',
  fieldset)
  >> >>           
   self.assertInHTML('',
  fieldset)
  >> >>
  >> >>
  >> >> First input is to have a working
  exemple, second is taken as is from
  >> >> my view. Not closing the input in
  assertInHTML give an error `Couldn't
  >> >> find '
  >> >> errors with assertContains(*args,
  html=True)
  >> >>
  >> >> I could copy/past the input directly
  in my test but if the maxlength
  >> >> or class attribute change, the test
  will break. Taking the input
  >> >> directly from the django form will
  test if the django form is rendered
  >> >> in the view, not if the view is
  displaying a suitable form.
  >> >>
  >> >> 

Re: Testing an object

2016-08-01 Thread Neil Hunt
That was an silly basic python mistake. Doh! I just indented the method 
correctly and the test ran fine. Thanks a lot, ludovic :)

On Monday, August 1, 2016 at 12:58:01 PM UTC+1, ludovic coues wrote:
>
> Look like you forget to indent the method inside your class. 
>
> 2016-08-01 13:43 GMT+02:00 Neil Hunt : 
> > I've read and reread the tutorial and I'm working on writing a very 
> simple 
> > banking app by copying and modifying what's in the tutorial. I've 
> started a 
> > new project and copied what was on the first two pages of the tutorial 
> and 
> > I've written a new models file. Make migrations works okay with the new 
> > models. I tried testing these new models using the test below and the 
> > console came up with an attribute error. Did I make a stupid mistake 
> > somewhere? Any help would be much appreciated. 
> > 
> > Traceback (most recent call last): 
> >   File "/home/DJapps/banking/mybank/banking/test_models.py", line 12, in 
> > test_animals_can_speak 
> > self.assertEqual(person.get_first_name(), 'Bob') 
> > AttributeError: 'Person' object has no attribute 'get_first_name' 
> > 
> > 
> > from django.test import TestCase 
> > from banking.models import Person 
> > 
> > class PersonTestCase(TestCase): 
> > def setUp(self): 
> > Person.objects.create(first_name="Bob", last_name="Smith", 
> > login_name="myname", password="Dog") 
> > 
> > def test_animals_can_speak(self): 
> > """Animals that can speak are correctly identified""" 
> > person = Person.objects.get(first_name="Bob") 
> > #person = mommy.make(Person) 
> > self.assertEqual(person.get_first_name(), 'Bob') 
> > #self.assertEqual(person.get_last_name(), 'Smith') 
> > #self.assertEqual(person.get_login_name(), 'myname') 
> > #self.assertEqual(person.get_password(), 'Dog') 
> > #self.assertEqual(person._str__, person_text) 
> > 
> > New models... 
> > 
> > from django.db import models 
> > 
> > # Create your models here. 
> > class Person(models.Model): 
> > first_name = models.CharField(max_length=4,default="Bob") 
> > last_name = models.CharField(max_length=6,default="Smith") 
> > login_name = models.CharField(max_length=3,default="me") 
> > password = models.CharField(max_length=7, default="password") 
> > person_text = models.CharField(max_length=10, default="Bob Smith") 
> > 
> > def get_first_name(self): 
> > return self.first_name 
> > 
> > def get_last_name(self): 
> > return self.last_name 
> > 
> > def get_login_name(self): 
> > return self.login_name 
> > 
> > def get_password(self, user_input): 
> > return self.password 
> > 
> > def __str__(self): 
> > return self.person_text 
> > 
> > class Account1(models.Model): 
> > account_number = models.IntegerField(default=12345678) 
> > bank_balance = models.DecimalField(max_digits=4, decimal_places=2, 
> > default=12.99) 
> > interest_rate = models.IntegerField(default=2) 
> > account_text = models.CharField(max_length=16, default="Current 
> > Account") 
> > person = models.ForeignKey(Person, on_delete=models.CASCADE, 
> default="") 
> > 
> > 
> > def get_account_number(self): 
> > return self.account_number 
> > 
> > def get_bank_balance(self): 
> > return self.bank_balance 
> > 
> > def deposit(self, amount): 
> > self.bank_balance = self.bank_balance + amount 
> > return 
> > 
> > def get_interest_rate(self): 
> > return self.interest_rate 
> > 
> > def withdraw(self, amount): 
> > self.bank_balance = self.bank_balance - amount 
> > return 
> > 
> > def __str__(self): 
> > return self.account_text 
> > 
> > 
> > -- 
> > 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 https://groups.google.com/group/django-users. 
> > To view this discussion on the web visit 
> > 
> https://groups.google.com/d/msgid/django-users/1b946075-f532-408f-ace7-4e4361ad350b%40googlegroups.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/1d80f305-6e5e-4cbc-8a9a-623dd730651e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing an object

2016-08-01 Thread ludovic coues
Look like you forget to indent the method inside your class.

2016-08-01 13:43 GMT+02:00 Neil Hunt :
> I've read and reread the tutorial and I'm working on writing a very simple
> banking app by copying and modifying what's in the tutorial. I've started a
> new project and copied what was on the first two pages of the tutorial and
> I've written a new models file. Make migrations works okay with the new
> models. I tried testing these new models using the test below and the
> console came up with an attribute error. Did I make a stupid mistake
> somewhere? Any help would be much appreciated.
>
> Traceback (most recent call last):
>   File "/home/DJapps/banking/mybank/banking/test_models.py", line 12, in
> test_animals_can_speak
> self.assertEqual(person.get_first_name(), 'Bob')
> AttributeError: 'Person' object has no attribute 'get_first_name'
>
>
> from django.test import TestCase
> from banking.models import Person
>
> class PersonTestCase(TestCase):
> def setUp(self):
> Person.objects.create(first_name="Bob", last_name="Smith",
> login_name="myname", password="Dog")
>
> def test_animals_can_speak(self):
> """Animals that can speak are correctly identified"""
> person = Person.objects.get(first_name="Bob")
> #person = mommy.make(Person)
> self.assertEqual(person.get_first_name(), 'Bob')
> #self.assertEqual(person.get_last_name(), 'Smith')
> #self.assertEqual(person.get_login_name(), 'myname')
> #self.assertEqual(person.get_password(), 'Dog')
> #self.assertEqual(person._str__, person_text)
>
> New models...
>
> from django.db import models
>
> # Create your models here.
> class Person(models.Model):
> first_name = models.CharField(max_length=4,default="Bob")
> last_name = models.CharField(max_length=6,default="Smith")
> login_name = models.CharField(max_length=3,default="me")
> password = models.CharField(max_length=7, default="password")
> person_text = models.CharField(max_length=10, default="Bob Smith")
>
> def get_first_name(self):
> return self.first_name
>
> def get_last_name(self):
> return self.last_name
>
> def get_login_name(self):
> return self.login_name
>
> def get_password(self, user_input):
> return self.password
>
> def __str__(self):
> return self.person_text
>
> class Account1(models.Model):
> account_number = models.IntegerField(default=12345678)
> bank_balance = models.DecimalField(max_digits=4, decimal_places=2,
> default=12.99)
> interest_rate = models.IntegerField(default=2)
> account_text = models.CharField(max_length=16, default="Current
> Account")
> person = models.ForeignKey(Person, on_delete=models.CASCADE, default="")
>
>
> def get_account_number(self):
> return self.account_number
>
> def get_bank_balance(self):
> return self.bank_balance
>
> def deposit(self, amount):
> self.bank_balance = self.bank_balance + amount
> return
>
> def get_interest_rate(self):
> return self.interest_rate
>
> def withdraw(self, amount):
> self.bank_balance = self.bank_balance - amount
> return
>
> def __str__(self):
> return self.account_text
>
>
> --
> 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/1b946075-f532-408f-ace7-4e4361ad350b%40googlegroups.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%2BTbBCYYvU_Tw1Y_TBnmCWAt%2Bykh8Rhg%2B2aoMwZkEanYxPQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing if a view have an html element with at least one attribute

2016-07-31 Thread Andreas Kuhne
Jupp, thats about what I meant :-)

Probably the best way, if you don't want to check text.

Regards,

Andréas

2016-07-31 18:01 GMT+02:00 ludovic coues :

> Currently, I am using lxml. More dependencies but it's the cleanest
> method I've found currently.
> I use it like that:
>
> from django.test import TestCase
> from lxml import etree
>
> class FormTest(TestCase):
> def test_input(self):
> response = self.client.get('/accounts/login')
> self.assertEqual(response.status_code, 200)
> doc = etree.HTML(response.content)
>
> self.assertEqual(len(doc.findall('.//input[@name="username"]')), 1)
>
>
>
> 2016-07-31 17:46 GMT+02:00 Andreas Kuhne :
> > 2016-07-31 15:59 GMT+02:00 ludovic coues :
> >>
> >> Oh, sorry. A bit of misunderstanding and miscommunication on my part.
> >>
> >> The exemple I gave is just a quick way to reproduce my problem. The
> >> real test use self.client, reverse, cast response.content to a string.
> >> What I gave is a minimal exemple.
> >>
> >> Also, I assumed you talked about comparing bit of html element, not
> >> the raw content returned by the view. I'm quite uneasy to have the
> >> test failing if a class is added or removed from the element. But yes,
> >> your solution work for the current state of the application.
> >>
> >> 2016-07-31 14:46 GMT+02:00 Andreas Kuhne :
> >> > 2016-07-31 13:56 GMT+02:00 ludovic coues :
> >> >>
> >> >> First, thanks for the suggestion.
> >> >>
> >> >> I just tried that, didn't work.
> >> >> Here is the test file I used:
> >> >>
> >> >>
> >> >> from django.test import TestCase
> >> >>
> >> >> class HTMLTestCase(TestCase):
> >> >>
> >> >> def test_input_in_fieldset(self):
> >> >> fieldset = """
> >> >> 
> >> >> 
> >> >>  >> >> maxlength="254" name="username" rows="3" type="text" required />
> >> >> 
> >> >> """
> >> >> self.assertInHTML('', fieldset)
> >> >> self.assertInHTML('', fieldset)
> >> >>
> >> >>
> >> >> First input is to have a working exemple, second is taken as is from
> >> >> my view. Not closing the input in assertInHTML give an error
> `Couldn't
> >> >> find ' same
> >> >> errors with assertContains(*args, html=True)
> >> >>
> >> >> I could copy/past the input directly in my test but if the maxlength
> >> >> or class attribute change, the test will break. Taking the input
> >> >> directly from the django form will test if the django form is
> rendered
> >> >> in the view, not if the view is displaying a suitable form.
> >> >>
> >> >> 2016-07-31 13:22 GMT+02:00 Andreas Kuhne  >:
> >> >> > 2016-07-31 12:38 GMT+02:00 ludovic coues :
> >> >> >>
> >> >> >> Hello,
> >> >> >>
> >> >> >> I am trying to test if a view is displaying a form with an input
> >> >> >> element with name=username.
> >> >> >>
> >> >> >> Currently, I have tried a lot of variation around
> >> >> >> `self.assertContains( response, "",
> >> >> >> html=True)` but none work.
> >> >> >> I assume that doesn't work because the view have a field input
> with
> >> >> >> name=username but also autofocus="", a class and a bunch of other
> >> >> >> attribute.
> >> >> >>
> >> >> >> I could extract the form from the context and check the field
> >> >> >> username
> >> >> >> from the form is displayed in the view but I'm not ok with that
> >> >> >> solution. I'm testing if there is a input with name=username, not
> a
> >> >> >> bunch of unrelated attribute.
> >> >> >>
> >> >> >> I could also use a LiveServerTestCase and selenium but that look
> >> >> >> like
> >> >> >> a bit overkill for my need. lxml is another option but it would
> >> >> >> bring
> >> >> >> more dependencies.
> >> >> >>
> >> >> >> A bit of help would be welcome :)
> >> >> >>
> >> >> >>
> >> >> >>
> >> >> >> --
> >> >> >>
> >> >> >> 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%2BTah74hdZMv%2BwdZPPq5PLaJ%3DhxOFMNXuVLfFYSw2Uz4N0w%40mail.gmail.com
> .
> >> >> >> For more options, visit https://groups.google.com/d/optout.
> >> >> >
> >> >> >
> >> >> > Django usually creates the inputs the same way, so what I do in my
> >> >> > tests
> >> >> > is
> >> >> > to first dump the content of the response body 

Re: Testing if a view have an html element with at least one attribute

2016-07-31 Thread ludovic coues
Currently, I am using lxml. More dependencies but it's the cleanest
method I've found currently.
I use it like that:

from django.test import TestCase
from lxml import etree

class FormTest(TestCase):
def test_input(self):
response = self.client.get('/accounts/login')
self.assertEqual(response.status_code, 200)
doc = etree.HTML(response.content)
self.assertEqual(len(doc.findall('.//input[@name="username"]')), 1)



2016-07-31 17:46 GMT+02:00 Andreas Kuhne :
> 2016-07-31 15:59 GMT+02:00 ludovic coues :
>>
>> Oh, sorry. A bit of misunderstanding and miscommunication on my part.
>>
>> The exemple I gave is just a quick way to reproduce my problem. The
>> real test use self.client, reverse, cast response.content to a string.
>> What I gave is a minimal exemple.
>>
>> Also, I assumed you talked about comparing bit of html element, not
>> the raw content returned by the view. I'm quite uneasy to have the
>> test failing if a class is added or removed from the element. But yes,
>> your solution work for the current state of the application.
>>
>> 2016-07-31 14:46 GMT+02:00 Andreas Kuhne :
>> > 2016-07-31 13:56 GMT+02:00 ludovic coues :
>> >>
>> >> First, thanks for the suggestion.
>> >>
>> >> I just tried that, didn't work.
>> >> Here is the test file I used:
>> >>
>> >>
>> >> from django.test import TestCase
>> >>
>> >> class HTMLTestCase(TestCase):
>> >>
>> >> def test_input_in_fieldset(self):
>> >> fieldset = """
>> >> 
>> >> 
>> >> > >> maxlength="254" name="username" rows="3" type="text" required />
>> >> 
>> >> """
>> >> self.assertInHTML('', fieldset)
>> >> self.assertInHTML('', fieldset)
>> >>
>> >>
>> >> First input is to have a working exemple, second is taken as is from
>> >> my view. Not closing the input in assertInHTML give an error `Couldn't
>> >> find '> >> errors with assertContains(*args, html=True)
>> >>
>> >> I could copy/past the input directly in my test but if the maxlength
>> >> or class attribute change, the test will break. Taking the input
>> >> directly from the django form will test if the django form is rendered
>> >> in the view, not if the view is displaying a suitable form.
>> >>
>> >> 2016-07-31 13:22 GMT+02:00 Andreas Kuhne :
>> >> > 2016-07-31 12:38 GMT+02:00 ludovic coues :
>> >> >>
>> >> >> Hello,
>> >> >>
>> >> >> I am trying to test if a view is displaying a form with an input
>> >> >> element with name=username.
>> >> >>
>> >> >> Currently, I have tried a lot of variation around
>> >> >> `self.assertContains( response, "",
>> >> >> html=True)` but none work.
>> >> >> I assume that doesn't work because the view have a field input with
>> >> >> name=username but also autofocus="", a class and a bunch of other
>> >> >> attribute.
>> >> >>
>> >> >> I could extract the form from the context and check the field
>> >> >> username
>> >> >> from the form is displayed in the view but I'm not ok with that
>> >> >> solution. I'm testing if there is a input with name=username, not a
>> >> >> bunch of unrelated attribute.
>> >> >>
>> >> >> I could also use a LiveServerTestCase and selenium but that look
>> >> >> like
>> >> >> a bit overkill for my need. lxml is another option but it would
>> >> >> bring
>> >> >> more dependencies.
>> >> >>
>> >> >> A bit of help would be welcome :)
>> >> >>
>> >> >>
>> >> >>
>> >> >> --
>> >> >>
>> >> >> 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%2BTah74hdZMv%2BwdZPPq5PLaJ%3DhxOFMNXuVLfFYSw2Uz4N0w%40mail.gmail.com.
>> >> >> For more options, visit https://groups.google.com/d/optout.
>> >> >
>> >> >
>> >> > Django usually creates the inputs the same way, so what I do in my
>> >> > tests
>> >> > is
>> >> > to first dump the content of the response body on the screen and then
>> >> > copy
>> >> > the input statement from there. What you probably need is '> >> > name="username"', because it doesn't matter for your test if the html
>> >> > tag is
>> >> > closed. So you should be fine with:
>> >> > self.assertContains(response, '> >> >
>> >> > --
>> >> > You received this message because you are subscribed to the Google
>> >> > Groups
>> >> > "Django users" group.
>> >> > To 

Re: Testing if a view have an html element with at least one attribute

2016-07-31 Thread Andreas Kuhne
2016-07-31 15:59 GMT+02:00 ludovic coues :

> Oh, sorry. A bit of misunderstanding and miscommunication on my part.
>
> The exemple I gave is just a quick way to reproduce my problem. The
> real test use self.client, reverse, cast response.content to a string.
> What I gave is a minimal exemple.
>
> Also, I assumed you talked about comparing bit of html element, not
> the raw content returned by the view. I'm quite uneasy to have the
> test failing if a class is added or removed from the element. But yes,
> your solution work for the current state of the application.
>
> 2016-07-31 14:46 GMT+02:00 Andreas Kuhne :
> > 2016-07-31 13:56 GMT+02:00 ludovic coues :
> >>
> >> First, thanks for the suggestion.
> >>
> >> I just tried that, didn't work.
> >> Here is the test file I used:
> >>
> >>
> >> from django.test import TestCase
> >>
> >> class HTMLTestCase(TestCase):
> >>
> >> def test_input_in_fieldset(self):
> >> fieldset = """
> >> 
> >> 
> >>  >> maxlength="254" name="username" rows="3" type="text" required />
> >> 
> >> """
> >> self.assertInHTML('', fieldset)
> >> self.assertInHTML('', fieldset)
> >>
> >>
> >> First input is to have a working exemple, second is taken as is from
> >> my view. Not closing the input in assertInHTML give an error `Couldn't
> >> find ' >> errors with assertContains(*args, html=True)
> >>
> >> I could copy/past the input directly in my test but if the maxlength
> >> or class attribute change, the test will break. Taking the input
> >> directly from the django form will test if the django form is rendered
> >> in the view, not if the view is displaying a suitable form.
> >>
> >> 2016-07-31 13:22 GMT+02:00 Andreas Kuhne :
> >> > 2016-07-31 12:38 GMT+02:00 ludovic coues :
> >> >>
> >> >> Hello,
> >> >>
> >> >> I am trying to test if a view is displaying a form with an input
> >> >> element with name=username.
> >> >>
> >> >> Currently, I have tried a lot of variation around
> >> >> `self.assertContains( response, "",
> >> >> html=True)` but none work.
> >> >> I assume that doesn't work because the view have a field input with
> >> >> name=username but also autofocus="", a class and a bunch of other
> >> >> attribute.
> >> >>
> >> >> I could extract the form from the context and check the field
> username
> >> >> from the form is displayed in the view but I'm not ok with that
> >> >> solution. I'm testing if there is a input with name=username, not a
> >> >> bunch of unrelated attribute.
> >> >>
> >> >> I could also use a LiveServerTestCase and selenium but that look like
> >> >> a bit overkill for my need. lxml is another option but it would bring
> >> >> more dependencies.
> >> >>
> >> >> A bit of help would be welcome :)
> >> >>
> >> >>
> >> >>
> >> >> --
> >> >>
> >> >> 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%2BTah74hdZMv%2BwdZPPq5PLaJ%3DhxOFMNXuVLfFYSw2Uz4N0w%40mail.gmail.com
> .
> >> >> For more options, visit https://groups.google.com/d/optout.
> >> >
> >> >
> >> > Django usually creates the inputs the same way, so what I do in my
> tests
> >> > is
> >> > to first dump the content of the response body on the screen and then
> >> > copy
> >> > the input statement from there. What you probably need is ' >> > name="username"', because it doesn't matter for your test if the html
> >> > tag is
> >> > closed. So you should be fine with:
> >> > self.assertContains(response, ' >> >
> >> > --
> >> > 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/CALXYUbmmotLwzjZY6ZZnAqy21xqZN1%3DiE7ah3g5JxFgEw-POZg%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

Re: Testing if a view have an html element with at least one attribute

2016-07-31 Thread ludovic coues
Oh, sorry. A bit of misunderstanding and miscommunication on my part.

The exemple I gave is just a quick way to reproduce my problem. The
real test use self.client, reverse, cast response.content to a string.
What I gave is a minimal exemple.

Also, I assumed you talked about comparing bit of html element, not
the raw content returned by the view. I'm quite uneasy to have the
test failing if a class is added or removed from the element. But yes,
your solution work for the current state of the application.

2016-07-31 14:46 GMT+02:00 Andreas Kuhne :
> 2016-07-31 13:56 GMT+02:00 ludovic coues :
>>
>> First, thanks for the suggestion.
>>
>> I just tried that, didn't work.
>> Here is the test file I used:
>>
>>
>> from django.test import TestCase
>>
>> class HTMLTestCase(TestCase):
>>
>> def test_input_in_fieldset(self):
>> fieldset = """
>> 
>> 
>> > maxlength="254" name="username" rows="3" type="text" required />
>> 
>> """
>> self.assertInHTML('', fieldset)
>> self.assertInHTML('', fieldset)
>>
>>
>> First input is to have a working exemple, second is taken as is from
>> my view. Not closing the input in assertInHTML give an error `Couldn't
>> find '> errors with assertContains(*args, html=True)
>>
>> I could copy/past the input directly in my test but if the maxlength
>> or class attribute change, the test will break. Taking the input
>> directly from the django form will test if the django form is rendered
>> in the view, not if the view is displaying a suitable form.
>>
>> 2016-07-31 13:22 GMT+02:00 Andreas Kuhne :
>> > 2016-07-31 12:38 GMT+02:00 ludovic coues :
>> >>
>> >> Hello,
>> >>
>> >> I am trying to test if a view is displaying a form with an input
>> >> element with name=username.
>> >>
>> >> Currently, I have tried a lot of variation around
>> >> `self.assertContains( response, "",
>> >> html=True)` but none work.
>> >> I assume that doesn't work because the view have a field input with
>> >> name=username but also autofocus="", a class and a bunch of other
>> >> attribute.
>> >>
>> >> I could extract the form from the context and check the field username
>> >> from the form is displayed in the view but I'm not ok with that
>> >> solution. I'm testing if there is a input with name=username, not a
>> >> bunch of unrelated attribute.
>> >>
>> >> I could also use a LiveServerTestCase and selenium but that look like
>> >> a bit overkill for my need. lxml is another option but it would bring
>> >> more dependencies.
>> >>
>> >> A bit of help would be welcome :)
>> >>
>> >>
>> >>
>> >> --
>> >>
>> >> 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%2BTah74hdZMv%2BwdZPPq5PLaJ%3DhxOFMNXuVLfFYSw2Uz4N0w%40mail.gmail.com.
>> >> For more options, visit https://groups.google.com/d/optout.
>> >
>> >
>> > Django usually creates the inputs the same way, so what I do in my tests
>> > is
>> > to first dump the content of the response body on the screen and then
>> > copy
>> > the input statement from there. What you probably need is '> > name="username"', because it doesn't matter for your test if the html
>> > tag is
>> > closed. So you should be fine with:
>> > self.assertContains(response, '> >
>> > --
>> > 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/CALXYUbmmotLwzjZY6ZZnAqy21xqZN1%3DiE7ah3g5JxFgEw-POZg%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 

Re: Testing if a view have an html element with at least one attribute

2016-07-31 Thread Andreas Kuhne
2016-07-31 13:56 GMT+02:00 ludovic coues :

> First, thanks for the suggestion.
>
> I just tried that, didn't work.
> Here is the test file I used:
>
>
> from django.test import TestCase
>
> class HTMLTestCase(TestCase):
>
> def test_input_in_fieldset(self):
> fieldset = """
> 
> 
>  maxlength="254" name="username" rows="3" type="text" required />
> 
> """
> self.assertInHTML('', fieldset)
> self.assertInHTML('', fieldset)
>
>
> First input is to have a working exemple, second is taken as is from
> my view. Not closing the input in assertInHTML give an error `Couldn't
> find ' errors with assertContains(*args, html=True)
>
> I could copy/past the input directly in my test but if the maxlength
> or class attribute change, the test will break. Taking the input
> directly from the django form will test if the django form is rendered
> in the view, not if the view is displaying a suitable form.
>
> 2016-07-31 13:22 GMT+02:00 Andreas Kuhne :
> > 2016-07-31 12:38 GMT+02:00 ludovic coues :
> >>
> >> Hello,
> >>
> >> I am trying to test if a view is displaying a form with an input
> >> element with name=username.
> >>
> >> Currently, I have tried a lot of variation around
> >> `self.assertContains( response, "",
> >> html=True)` but none work.
> >> I assume that doesn't work because the view have a field input with
> >> name=username but also autofocus="", a class and a bunch of other
> >> attribute.
> >>
> >> I could extract the form from the context and check the field username
> >> from the form is displayed in the view but I'm not ok with that
> >> solution. I'm testing if there is a input with name=username, not a
> >> bunch of unrelated attribute.
> >>
> >> I could also use a LiveServerTestCase and selenium but that look like
> >> a bit overkill for my need. lxml is another option but it would bring
> >> more dependencies.
> >>
> >> A bit of help would be welcome :)
> >>
> >>
> >>
> >> --
> >>
> >> 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%2BTah74hdZMv%2BwdZPPq5PLaJ%3DhxOFMNXuVLfFYSw2Uz4N0w%40mail.gmail.com
> .
> >> For more options, visit https://groups.google.com/d/optout.
> >
> >
> > Django usually creates the inputs the same way, so what I do in my tests
> is
> > to first dump the content of the response body on the screen and then
> copy
> > the input statement from there. What you probably need is ' > name="username"', because it doesn't matter for your test if the html
> tag is
> > closed. So you should be fine with:
> > self.assertContains(response, ' >
> > --
> > 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/CALXYUbmmotLwzjZY6ZZnAqy21xqZN1%3DiE7ah3g5JxFgEw-POZg%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%2BTZCWDkkrZuP2N168pth1hL-gc8FrVjMwZnb3xS%2BK1X%2Bxw%40mail.gmail.com
> .
> For more options, visit https://groups.google.com/d/optout.
>

Hi,

I think you have misunderstood me.

First you need to check against the real response object, otherwise your
test will only test if the item is present in your string, which is not
what I meant. I meant that you should check what HTML django is generating
to then get the correct information.

In your case, I am now guessing that the output of django is the
information you put into the fieldset variable?

If so, you need to write
self.assertContains(response,'https://groups.google.com/group/django-users.
To view 

Re: Testing if a view have an html element with at least one attribute

2016-07-31 Thread ludovic coues
First, thanks for the suggestion.

I just tried that, didn't work.
Here is the test file I used:


from django.test import TestCase

class HTMLTestCase(TestCase):

def test_input_in_fieldset(self):
fieldset = """




"""
self.assertInHTML('', fieldset)
self.assertInHTML('', fieldset)


First input is to have a working exemple, second is taken as is from
my view. Not closing the input in assertInHTML give an error `Couldn't
find ':
> 2016-07-31 12:38 GMT+02:00 ludovic coues :
>>
>> Hello,
>>
>> I am trying to test if a view is displaying a form with an input
>> element with name=username.
>>
>> Currently, I have tried a lot of variation around
>> `self.assertContains( response, "",
>> html=True)` but none work.
>> I assume that doesn't work because the view have a field input with
>> name=username but also autofocus="", a class and a bunch of other
>> attribute.
>>
>> I could extract the form from the context and check the field username
>> from the form is displayed in the view but I'm not ok with that
>> solution. I'm testing if there is a input with name=username, not a
>> bunch of unrelated attribute.
>>
>> I could also use a LiveServerTestCase and selenium but that look like
>> a bit overkill for my need. lxml is another option but it would bring
>> more dependencies.
>>
>> A bit of help would be welcome :)
>>
>>
>>
>> --
>>
>> 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%2BTah74hdZMv%2BwdZPPq5PLaJ%3DhxOFMNXuVLfFYSw2Uz4N0w%40mail.gmail.com.
>> For more options, visit https://groups.google.com/d/optout.
>
>
> Django usually creates the inputs the same way, so what I do in my tests is
> to first dump the content of the response body on the screen and then copy
> the input statement from there. What you probably need is ' name="username"', because it doesn't matter for your test if the html tag is
> closed. So you should be fine with:
> self.assertContains(response, '
> --
> 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/CALXYUbmmotLwzjZY6ZZnAqy21xqZN1%3DiE7ah3g5JxFgEw-POZg%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%2BTZCWDkkrZuP2N168pth1hL-gc8FrVjMwZnb3xS%2BK1X%2Bxw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing if a view have an html element with at least one attribute

2016-07-31 Thread Andreas Kuhne
2016-07-31 12:38 GMT+02:00 ludovic coues :

> Hello,
>
> I am trying to test if a view is displaying a form with an input
> element with name=username.
>
> Currently, I have tried a lot of variation around
> `self.assertContains( response, "",
> html=True)` but none work.
> I assume that doesn't work because the view have a field input with
> name=username but also autofocus="", a class and a bunch of other
> attribute.
>
> I could extract the form from the context and check the field username
> from the form is displayed in the view but I'm not ok with that
> solution. I'm testing if there is a input with name=username, not a
> bunch of unrelated attribute.
>
> I could also use a LiveServerTestCase and selenium but that look like
> a bit overkill for my need. lxml is another option but it would bring
> more dependencies.
>
> A bit of help would be welcome :)
>
>
>
> --
>
> 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%2BTah74hdZMv%2BwdZPPq5PLaJ%3DhxOFMNXuVLfFYSw2Uz4N0w%40mail.gmail.com
> .
> For more options, visit https://groups.google.com/d/optout.
>

Django usually creates the inputs the same way, so what I do in my tests is
to first dump the content of the response body on the screen and then copy
the input statement from there. What you probably need is 'https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CALXYUbmmotLwzjZY6ZZnAqy21xqZN1%3DiE7ah3g5JxFgEw-POZg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing the interaction of multiple sites

2016-01-04 Thread Nikolas Stevenson-Molnar
On Monday, January 4, 2016 at 3:39:22 PM UTC-8, Michal Petrucha wrote:
>
> Hi Nikolas, 
>
> Thanks for your suggestion, unfortunately, I don't see how it helps in 
> my case. 
>
> What I'm after is some kind of integration test: when I try to load a 
> page form the relying instance, verify that it gets redirected to the 
> provider, and then it gets redirected back with the correct callback 
> parameters. In both cases I need to actually hit the respective server 
> running a Django app, since it involves side effects (and side 
> conditions), such as whether the user is logged in on the provider, 
> and some in-database state changes to verify that the callback was 
> valid. 
>
> I don't see how mocking a HTTP response would help me with this, but, 
> of course, I may be missing something here. 
>
> Cheers, 
>
> Michal 
>

Sorry, I just misunderstood the question. I was thinking of unit tests, in 
which you'd want to remove as many external components as possible. 

-- 
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/ad81c184-e315-4ada-92f0-23cf7cf86259%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing the interaction of multiple sites

2016-01-04 Thread Michal Petrucha
On Mon, Jan 04, 2016 at 03:22:10PM -0800, Nikolas Stevenson-Molnar wrote:
> HTTPretty may help with this. It will let you mock a response from the 
> second server: https://github.com/gabrielfalcao/httpretty
> 
> _Nik

Hi Nikolas,

Thanks for your suggestion, unfortunately, I don't see how it helps in
my case.

What I'm after is some kind of integration test: when I try to load a
page form the relying instance, verify that it gets redirected to the
provider, and then it gets redirected back with the correct callback
parameters. In both cases I need to actually hit the respective server
running a Django app, since it involves side effects (and side
conditions), such as whether the user is logged in on the provider,
and some in-database state changes to verify that the callback was
valid.

I don't see how mocking a HTTP response would help me with this, but,
of course, I may be missing something here.

Cheers,

Michal

-- 
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/20160104233809.GB20308%40konk.org.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Digital signature


Re: Testing the interaction of multiple sites

2016-01-04 Thread Nikolas Stevenson-Molnar
HTTPretty may help with this. It will let you mock a response from the 
second server: https://github.com/gabrielfalcao/httpretty

_Nik

On Monday, January 4, 2016 at 2:50:05 PM UTC-8, Michal Petrucha wrote:
>
> Hi folks, 
>
> I'd like to write some tests for a simple redirect-based SSO solution, 
> in which there's one instance of an app responsible for 
> authentication, and all other instances redirect new sessionless users 
> to it, and then expect a redirect callback. Kind of like a simplified 
> version of OAuth in which there's no need for the relying party to 
> make a background request to the identity provider, since the provider 
> and the relying party share the same database. Each instance has its 
> own settings, SITE_ID and such. 
>
> I was thinking about using Selenium with LiveServerTestCase for this; 
> however, I'd need to have both the provider and the relying instance 
> listening at the same time. 
>
> Is there a simple mechanism to have LiveServerTestCase run two 
> separate server threads with different settings? Is there some kind of 
> third-party testing package that can do that? 
>
> Cheers, and have a happy New Year. 
>
> Michal 
>

-- 
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/3a60e98b-5660-4e39-b671-d8a42aa7f3f7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing the interaction of multiple sites

2016-01-04 Thread Nikolas Stevenson-Molnar
HTTPretty may help with this. It will let you mock a response from the second 
server: https://github.com/gabrielfalcao/httpretty

_Nik

On 1/4/2016 2:49:34 PM, Michal Petrucha  wrote:
Hi folks,

I'd like to write some tests for a simple redirect-based SSO solution,
in which there's one instance of an app responsible for
authentication, and all other instances redirect new sessionless users
to it, and then expect a redirect callback. Kind of like a simplified
version of OAuth in which there's no need for the relying party to
make a background request to the identity provider, since the provider
and the relying party share the same database. Each instance has its
own settings, SITE_ID and such.

I was thinking about using Selenium with LiveServerTestCase for this;
however, I'd need to have both the provider and the relying instance
listening at the same time.

Is there a simple mechanism to have LiveServerTestCase run two
separate server threads with different settings? Is there some kind of
third-party testing package that can do that?

Cheers, and have a happy New Year.

Michal

--
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/20160104224904.GA20308%40konk.org.
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/d9f6f506-0fdc-4a92-aa8e-385d486635f8%40getmailbird.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing django migrations

2015-12-27 Thread Gergely Polonkai
I'm also interested in that, except that I'd like to test RunPython steps.
On Dec 28, 2015 12:32 AM, "Dan Tagg"  wrote:

> Hi,
>
> I used this:
> https://github.com/plumdog/django_migration_testcase
>
> It's only worth writing tests if you are modifying code created by
> makemigrations.
>
> Dan
>
> On 27 December 2015 at 10:14, varun naganathan <
> varunnaganathan...@gmail.com> wrote:
>
>> Hi,I wanted to know how am i supposed to test the working of django
>> migrations.As in how the migrations generate the SQL query.Basically I want
>> to inspect how the sql query generated as in the output of "./manage.py
>> sqlmigrate" is being generated.I've generally used "pdb" along wth
>> unittest.TestCase,but for migrations I'm pretty much stuck.Does anyone
>> probably have a sample test they wrote to test the django migrations.
>> 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 https://groups.google.com/group/django-users.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/b6364f7e-56ab-4682-ad0a-3684e6199c8f%40googlegroups.com
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
>
> --
> Wildman and Herring Limited, Registered Office: 52 Great Eastern Street,
> London, EC2A 3EP, Company no: 05766374
>
> --
> 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/CAPZHCY5CJ_9jex%2BnKNi%3DCy2XG9X9zrLS%3DJBW-mUmDoCpK6%2BTPA%40mail.gmail.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/CACczBUL7z8M8nPbsAO2jM2EvyMCqxT4JJVGGSvA8MW__a8E6VQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing django migrations

2015-12-27 Thread Dan Tagg
Hi,

I used this:
https://github.com/plumdog/django_migration_testcase

It's only worth writing tests if you are modifying code created by
makemigrations.

Dan

On 27 December 2015 at 10:14, varun naganathan  wrote:

> Hi,I wanted to know how am i supposed to test the working of django
> migrations.As in how the migrations generate the SQL query.Basically I want
> to inspect how the sql query generated as in the output of "./manage.py
> sqlmigrate" is being generated.I've generally used "pdb" along wth
> unittest.TestCase,but for migrations I'm pretty much stuck.Does anyone
> probably have a sample test they wrote to test the django migrations.
> 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 https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/b6364f7e-56ab-4682-ad0a-3684e6199c8f%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Wildman and Herring Limited, Registered Office: 52 Great Eastern Street,
London, EC2A 3EP, Company no: 05766374

-- 
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/CAPZHCY5CJ_9jex%2BnKNi%3DCy2XG9X9zrLS%3DJBW-mUmDoCpK6%2BTPA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing related models without saving

2015-07-30 Thread Michael Herrmann
I'm very relieved - thanks Tim! If I can help, please let me know.

Best,
Michael

On 30 July 2015 at 17:56, Tim Graham  wrote:

> We are working on that solution:
> https://github.com/django/django/pull/5060
>
>
> On Thursday, July 30, 2015 at 7:19:31 AM UTC-4, mic...@herrmann.io wrote:
>>
>> Hi all,
>>
>> I've just been bitten by this new "feature" as well. I completely don't
>> understand this design decision of 1.8. It is very useful to be able to
>> create model classes without having to save them to the database, not just
>> for unit tests but also for experimenting in the shell. The new "feature"
>> breaks this which is a huge PITA, in my opinion.
>>
>> Could the check for RelatedObjectDoesNotExist not be performed in the
>> save(...) method by Django? Then we would get the best of both worlds: You
>> can create models however you like in unit tests or the shell, and at the
>> same time if you erroneously attempt to save a foreign key which doesn't
>> yet exist you would get the exception.
>>
>> I feel strongly about this because it is very much against the ease of
>> use which I like so much about Django. Is this the appropriate forum to
>> request this as a feature for 1.9 (or another future Django version)?
>>
>> Thanks,
>> Michael
>>
>> On Thursday, 16 July 2015 18:37:39 UTC+2, Carl Meyer wrote:
>>>
>>> Hi Roland,
>>>
>>> On 07/16/2015 07:46 AM, Roland Swingler wrote:
>>> >> i'll just say that Django tests don't favor too much into the "unit"
>>> > test spectrum;
>>> >
>>> > That is what I'm seeing - it is the same with rails out of the box as
>>> > well. I guess I'm just curious to know whether:
>>> >
>>> > a) the 'unit' test end of the spectrum is feasible if that's what you
>>> like
>>> > b) what is available in the Django community (if anything, whether
>>> > libraries, 'ways-of-doing-things' etc.) to support this if it is an
>>> > approach one wants to take.
>>>
>>> I also write model tests using unsaved models where possible. I don't
>>> think it has significant test isolation benefits (your tests are still
>>> integrating with most of the ORM), but it does have test-suite speed
>>> benefits!
>>>
>>> I understand why the change was made in 1.8 to disallow assigning an
>>> unsaved object to a ForeignKey/OneToOneField attribute; in production
>>> code that would almost always be a bug. Personally, though, I've never
>>> been bitten by that bug, I'm confident I could easily find and fix such
>>> a bug if I did write it, and I don't want to give up the ability to use
>>> related unsaved models in tests. So I just use my own subclasses of
>>> ForeignKey and OneToOneField with `allow_unsaved_instance_assignment =
>>> True` set on them (essentially reverting the safety change in 1.8). I
>>> haven't attempted to switch it on dynamically for testing; that should
>>> be possible using a setting and a custom subclass, but I wouldn't choose
>>> to do that; differences between test and production behavior should be
>>> minimized.
>>>
>>> Carl
>>>
>>>


-- 
[image: Inline image 1]

Michael Herrmann, MSc
Alser Straße 18/26
1090 Wien
Tel.: +43 699 11 65 16 40
Email: mich...@herrmann.io

-- 
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/CABrKpmDpe1DzPDj0TtC--cLx%3DpuesGF_WbeESj7tkYLAMeTYSA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing related models without saving

2015-07-30 Thread Tim Graham
We are working on that solution: https://github.com/django/django/pull/5060

On Thursday, July 30, 2015 at 7:19:31 AM UTC-4, mic...@herrmann.io wrote:
>
> Hi all,
>
> I've just been bitten by this new "feature" as well. I completely don't 
> understand this design decision of 1.8. It is very useful to be able to 
> create model classes without having to save them to the database, not just 
> for unit tests but also for experimenting in the shell. The new "feature" 
> breaks this which is a huge PITA, in my opinion.
>
> Could the check for RelatedObjectDoesNotExist not be performed in the 
> save(...) method by Django? Then we would get the best of both worlds: You 
> can create models however you like in unit tests or the shell, and at the 
> same time if you erroneously attempt to save a foreign key which doesn't 
> yet exist you would get the exception.
>
> I feel strongly about this because it is very much against the ease of use 
> which I like so much about Django. Is this the appropriate forum to request 
> this as a feature for 1.9 (or another future Django version)?
>
> Thanks,
> Michael
>
> On Thursday, 16 July 2015 18:37:39 UTC+2, Carl Meyer wrote:
>>
>> Hi Roland, 
>>
>> On 07/16/2015 07:46 AM, Roland Swingler wrote: 
>> >> i'll just say that Django tests don't favor too much into the "unit" 
>> > test spectrum; 
>> > 
>> > That is what I'm seeing - it is the same with rails out of the box as 
>> > well. I guess I'm just curious to know whether: 
>> > 
>> > a) the 'unit' test end of the spectrum is feasible if that's what you 
>> like 
>> > b) what is available in the Django community (if anything, whether 
>> > libraries, 'ways-of-doing-things' etc.) to support this if it is an 
>> > approach one wants to take. 
>>
>> I also write model tests using unsaved models where possible. I don't 
>> think it has significant test isolation benefits (your tests are still 
>> integrating with most of the ORM), but it does have test-suite speed 
>> benefits! 
>>
>> I understand why the change was made in 1.8 to disallow assigning an 
>> unsaved object to a ForeignKey/OneToOneField attribute; in production 
>> code that would almost always be a bug. Personally, though, I've never 
>> been bitten by that bug, I'm confident I could easily find and fix such 
>> a bug if I did write it, and I don't want to give up the ability to use 
>> related unsaved models in tests. So I just use my own subclasses of 
>> ForeignKey and OneToOneField with `allow_unsaved_instance_assignment = 
>> True` set on them (essentially reverting the safety change in 1.8). I 
>> haven't attempted to switch it on dynamically for testing; that should 
>> be possible using a setting and a custom subclass, but I wouldn't choose 
>> to do that; differences between test and production behavior should be 
>> minimized. 
>>
>> Carl 
>>
>>

-- 
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/24147436-a0fa-49c8-bd80-e4e74d052319%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing related models without saving

2015-07-30 Thread michael
Hi all,

I've just been bitten by this new "feature" as well. I completely don't 
understand this design decision of 1.8. It is very useful to be able to 
create model classes without having to save them to the database, not just 
for unit tests but also for experimenting in the shell. The new "feature" 
breaks this which is a huge PITA, in my opinion.

Could the check for RelatedObjectDoesNotExist not be performed in the 
save(...) method by Django? Then we would get the best of both worlds: You 
can create models however you like in unit tests or the shell, and at the 
same time if you erroneously attempt to save a foreign key which doesn't 
yet exist you would get the exception.

I feel strongly about this because it is very much against the ease of use 
which I like so much about Django. Is this the appropriate forum to request 
this as a feature for 1.9 (or another future Django version)?

Thanks,
Michael

On Thursday, 16 July 2015 18:37:39 UTC+2, Carl Meyer wrote:
>
> Hi Roland, 
>
> On 07/16/2015 07:46 AM, Roland Swingler wrote: 
> >> i'll just say that Django tests don't favor too much into the "unit" 
> > test spectrum; 
> > 
> > That is what I'm seeing - it is the same with rails out of the box as 
> > well. I guess I'm just curious to know whether: 
> > 
> > a) the 'unit' test end of the spectrum is feasible if that's what you 
> like 
> > b) what is available in the Django community (if anything, whether 
> > libraries, 'ways-of-doing-things' etc.) to support this if it is an 
> > approach one wants to take. 
>
> I also write model tests using unsaved models where possible. I don't 
> think it has significant test isolation benefits (your tests are still 
> integrating with most of the ORM), but it does have test-suite speed 
> benefits! 
>
> I understand why the change was made in 1.8 to disallow assigning an 
> unsaved object to a ForeignKey/OneToOneField attribute; in production 
> code that would almost always be a bug. Personally, though, I've never 
> been bitten by that bug, I'm confident I could easily find and fix such 
> a bug if I did write it, and I don't want to give up the ability to use 
> related unsaved models in tests. So I just use my own subclasses of 
> ForeignKey and OneToOneField with `allow_unsaved_instance_assignment = 
> True` set on them (essentially reverting the safety change in 1.8). I 
> haven't attempted to switch it on dynamically for testing; that should 
> be possible using a setting and a custom subclass, but I wouldn't choose 
> to do that; differences between test and production behavior should be 
> minimized. 
>
> Carl 
>
>

-- 
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/acbdd6a3-077e-43d2-bb42-72ecf235bcb4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing related models without saving

2015-07-16 Thread Carl Meyer
Hi Roland,

On 07/16/2015 07:46 AM, Roland Swingler wrote:
>> i'll just say that Django tests don't favor too much into the "unit"
> test spectrum;
> 
> That is what I'm seeing - it is the same with rails out of the box as
> well. I guess I'm just curious to know whether:
> 
> a) the 'unit' test end of the spectrum is feasible if that's what you like
> b) what is available in the Django community (if anything, whether
> libraries, 'ways-of-doing-things' etc.) to support this if it is an
> approach one wants to take.

I also write model tests using unsaved models where possible. I don't
think it has significant test isolation benefits (your tests are still
integrating with most of the ORM), but it does have test-suite speed
benefits!

I understand why the change was made in 1.8 to disallow assigning an
unsaved object to a ForeignKey/OneToOneField attribute; in production
code that would almost always be a bug. Personally, though, I've never
been bitten by that bug, I'm confident I could easily find and fix such
a bug if I did write it, and I don't want to give up the ability to use
related unsaved models in tests. So I just use my own subclasses of
ForeignKey and OneToOneField with `allow_unsaved_instance_assignment =
True` set on them (essentially reverting the safety change in 1.8). I
haven't attempted to switch it on dynamically for testing; that should
be possible using a setting and a custom subclass, but I wouldn't choose
to do that; differences between test and production behavior should be
minimized.

Carl

-- 
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/55A7DDB4.9080506%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Testing related models without saving

2015-07-16 Thread Roland Swingler
> i'll just say that Django tests don't favor too much into the "unit" test 
spectrum;

That is what I'm seeing - it is the same with rails out of the box as well. 
I guess I'm just curious to know whether:

a) the 'unit' test end of the spectrum is feasible if that's what you like
b) what is available in the Django community (if anything, whether 
libraries, 'ways-of-doing-things' etc.) to support this if it is an 
approach one wants to take.

Thanks,
Roland

-- 
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/90102d23-297c-402a-8fe6-bfc3d4ad2f4b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing related models without saving

2015-07-16 Thread Javier Guerra Giraldez
On Thu, Jul 16, 2015 at 8:18 AM, Roland Swingler
 wrote:
> I understand that the test db uses a different schema (it's the same in
> rails), the point is to be able to run tests isolated from having a database
> at all.


there are several testing styles, each one with different dogmas.
discussions of the adequacy of them can get very heated and
non-productive.

one of these styles states that each test should be perfectly isolated
from any other conceivable source of errors, including the database,
and in fact stopping short of suspecting the base OS itself (usually).

without trying to get too deep in religious dogma, i'll just say that
Django tests don't favor too much into the "unit" test spectrum;
instead they lean somewhat towards the "integration" camp (although
not totally there, either).

in short, the database is considered a required infrastructure
service, and tests usually assume it works as expected.

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAFkDaoR08cr5DSFH9HOXXxXvdH2QwefE-xuO0yi8hDmf58bSNg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing related models without saving

2015-07-16 Thread Roland Swingler
Hi,

Thanks for the link - I'll investigate that further, especially as to 
whether you can set that dynamically.

I understand that the test db uses a different schema (it's the same in 
rails), the point is to be able to run tests isolated from having a 
database at all.

Thanks,
Roland

-- 
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/6607ea31-9966-4d67-b43f-1974c17b33cc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing related models without saving

2015-07-16 Thread Bruno A.
This might help 
maybe: 
https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey.allow_unsaved_instance_assignment

On Thursday, 16 July 2015 12:21:30 UTC+1, Roland Swingler wrote:
>
> Hi all,
>
> I've very recently come to to Django from a rails background, and 
> struggling to do unit testing of Django models without saving to the 
> database as I'm used to in Rails. Lets say you have 2 linked models, for 
> example User and UserProfileDetails, then in my tests I want to set up the 
> structure and not save any of it:
>
> user = User()
> user.profile_details = UserProfileDetails()
> ...
> # stuff that tests non-persistence related functionality
>
> But I don't seem to be able to do this, because it will raise a 
> RelatedObjectDoesNotExist error, saying UserProfileDetails has no user. 
> Obviously I can get around this by saving the user first, but if I want to 
> not touch the database in tests is there any way I can achieve this?
>
> (also apologies if this has been asked before - I did a quick search of 
> the archives and couldn't find anything).
>
> Thanks in advance,
> Roland
>

-- 
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/6fcb1249-6aab-4af6-b583-57ad18364419%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing related models without saving

2015-07-16 Thread Bruno A.
You did not quote your models, but I assume your UserProfileDetails has a 
OneToOne or ForeignKey relationship with User model.

With Django, you generally need to save the related model before adding it 
to the Foreignkey, as the relationship in UserProfileDetails is using the 
primary key (called id by default) from User instance, which is populated 
when the object is saved.

I don't quite understand why you don't want to save the User model first, 
the unit tests are running on a separate DB schema.

On Thursday, 16 July 2015 12:21:30 UTC+1, Roland Swingler wrote:
>
> Hi all,
>
> I've very recently come to to Django from a rails background, and 
> struggling to do unit testing of Django models without saving to the 
> database as I'm used to in Rails. Lets say you have 2 linked models, for 
> example User and UserProfileDetails, then in my tests I want to set up the 
> structure and not save any of it:
>
> user = User()
> user.profile_details = UserProfileDetails()
> ...
> # stuff that tests non-persistence related functionality
>
> But I don't seem to be able to do this, because it will raise a 
> RelatedObjectDoesNotExist error, saying UserProfileDetails has no user. 
> Obviously I can get around this by saving the user first, but if I want to 
> not touch the database in tests is there any way I can achieve this?
>
> (also apologies if this has been asked before - I did a quick search of 
> the archives and couldn't find anything).
>
> Thanks in advance,
> Roland
>

-- 
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/2e820843-6bd6-43aa-98fa-bdbf23574d3f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing a new app

2015-05-28 Thread Bill Freeman
If the "new" app doesn't need services from the larger app in order t work,
but rather the other way around, why not leave it separate, and later, just
make it an install requirement for the larger app?

On Thu, May 28, 2015 at 5:54 AM, Klaas Feenstra  wrote:

> Using GIT would be the way of working..
>
> On Thu, May 28, 2015 at 4:24 AM, DZ  wrote:
>
>> Greetings,
>>
>>  I want to start a new app that if it works out I will tie into a larger
>> django app. I do not really want the worlds to mix at the start just in
>> case I need scrap and start it over a few times. I was thinking the best
>> approach would be to create this first as a stand alone app and then when I
>> have the details worked out bring it under the larger app. When I bring it
>> under the larger app I know I would start the data over and use south to
>> bring the worlds together. I am developing under windows, django, python,
>> mysql, and I use south as my db migration tool. Does anyone forsee any
>> problems with this approach? Sorry if the question seems obvious or simple
>> just would like to travel the path of lower resistance as Im working out
>> the features/models of this new app.
>>
>> Thanks for any advice.
>>
>> DZ
>>
>> --
>> 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/81557fc6-48c7-4cea-ae9a-c5b49be06f82%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/CAJcivaembcZ%3DNtNxiWP%3Dr8e%3DHTfZfFLn4jYDCedcKiqS_vsb0A%40mail.gmail.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/CAB%2BAj0s2PnCaDnbR1_JU1r4mJh6reoeAOucL1-K6UR%3DTKO80sg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing a new app

2015-05-28 Thread Klaas Feenstra
Using GIT would be the way of working..

On Thu, May 28, 2015 at 4:24 AM, DZ  wrote:

> Greetings,
>
>  I want to start a new app that if it works out I will tie into a larger
> django app. I do not really want the worlds to mix at the start just in
> case I need scrap and start it over a few times. I was thinking the best
> approach would be to create this first as a stand alone app and then when I
> have the details worked out bring it under the larger app. When I bring it
> under the larger app I know I would start the data over and use south to
> bring the worlds together. I am developing under windows, django, python,
> mysql, and I use south as my db migration tool. Does anyone forsee any
> problems with this approach? Sorry if the question seems obvious or simple
> just would like to travel the path of lower resistance as Im working out
> the features/models of this new app.
>
> Thanks for any advice.
>
> DZ
>
> --
> 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/81557fc6-48c7-4cea-ae9a-c5b49be06f82%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/CAJcivaembcZ%3DNtNxiWP%3Dr8e%3DHTfZfFLn4jYDCedcKiqS_vsb0A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing Setup gives 500, but dev server works okay

2015-05-25 Thread Timothy W. Cook
I should add that the actual error is:

selenium.common.exceptions.NoSuchElementException: Message: Unable to
locate element: {"method":"id","selector":"id_login"}

because the main page never loads so it can't find the login button,


On Mon, May 25, 2015 at 12:29 PM, Timothy W. Cook  wrote:

> I have a project that I started, then decided I should apply a TDD
> approach.
>
> Well the user registration and login portion already works but I am
> attempting to add some tests to it.
> The user can register, is redirected back to the main page with a Login
> button.
>
> Here is the test code:
>
> def test_visitor_can_register_and_login_logout(self):
> self.browser.get(self.server_url)
> self.browser.find_element_by_id('id_register').click()
> self.browser.find_element_by_id('id_username').send_keys(TEST_USER)
> self.browser.find_element_by_id('id_email').send_keys(TEST_EMAIL)
>
> self.browser.find_element_by_id('id_password1').send_keys(TEST_PASSWORD)
>
> self.browser.find_element_by_id('id_password2').send_keys(TEST_PASSWORD)
> self.browser.find_element_by_id('submit_registration').click()
> time.sleep(10)
> ## Existing user is invited to login
> self.browser.find_element_by_id('id_login').click()
> self.browser.find_element_by_id('id_login').send_keys(TEST_USER)
>
> self.browser.find_element_by_id('id_password').send_keys(TEST_PASSWORD)
> self.browser.find_element_by_id('log_me_in').click()
>
> ## test user is logged in and can logout
> self.browser.find_element_by_id('id_logout').click()
> self.browser.find_element_by_tag_name('button').click()
> ##redirected back to main page
> self.browser.find_element_by_id('id_login')
>
> I see the main page load, the registration page loads and the inputs are
> filled in.
> When the submit_registion button is clicked I get a 500.  You can see I
> put a sleep in there just so I could see it and verify that the process
> isn't running too fast for the server to respond.
>
> I originally had the registration and login in separate tests but I
> understand that this might require TransactionTestCase ?  I am using
> from django.test import LiveServerTestCase in this class.
>
> I have one other test before that runs fine.
>
> Any ideas?  Tips on troubleshooting this functional test?
>
>
>
>
>
> 
> Timothy Cook
> LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook
> MLHIM http://www.mlhim.org
>
>


-- 


Timothy Cook
LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook
MLHIM http://www.mlhim.org

-- 
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/CA%2B%3DOU3UetYF2s47x3KiY%3D%3DZ8%3DYpCu%3Dc3L10z-XHOxBfUsHnRDw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing request parameters in Django (“+” behaves differently)

2015-04-20 Thread Eneko Illarramendi
Thank you Tom.

Somehow it seemed strange to test this view using client.get('/page/', {
'filter': 'one and two'})
but I get why it is like this.

Cheers,
Eneko


On Monday, April 20, 2015 at 3:30:55 PM UTC+2, Tom Evans wrote:
>
> On Sat, Apr 18, 2015 at 12:13 PM, Eneko Illarramendi 
>  wrote: 
> > Previously posted in SO: 
> > 
> http://stackoverflow.com/questions/29703930/testing-request-parameters-in-django-behaves-differently
>  
> > --- 
> > 
> > I have a Django View that uses a query parameter to so some content 
> > filtering. Something like this: 
> > 
> > /page/?filter=one+and+two 
> > /page/?filter=one,or,two 
> > 
> > I have noticed that Django converts the + to a space 
> > (request.GET.get('filter') returns one and two), and I´m OK with that. I 
> > just need to adjust the split() function I use in the View accordingly. 
>
> The arguments in a query string are urlencoded. Spaces are urlencoded 
> as '+'. Django's request.GET is a dict like object with the query 
> string arguments decoded. 
>
> > 
> > But... 
> > 
> > When I try to test this View, and I call: 
> > 
> > from django.test import Client 
> > client = Client() 
> > client.get('/page/', {'filter': 'one+and+two'}) 
>
> The test client takes a dictionary of raw strings, not urlencoded 
> strings. If you like, you are telling it to test the URL 
> '/page/?filter=one%2Band%2Btwo', as '+' is urlencoded as '%2B'. 
>
> Django is consistent, the test client takes raw un-encoded strings, 
> and request.GET delivers raw un-encoded strings. 
>
> Cheers 
>
> Tom 
>

-- 
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/274a6eb9-dfa5-42ba-aff9-d564fad4e0c4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing request parameters in Django (“+” behaves differently)

2015-04-20 Thread Tom Evans
On Sat, Apr 18, 2015 at 12:13 PM, Eneko Illarramendi
 wrote:
> Previously posted in SO:
> http://stackoverflow.com/questions/29703930/testing-request-parameters-in-django-behaves-differently
> ---
>
> I have a Django View that uses a query parameter to so some content
> filtering. Something like this:
>
> /page/?filter=one+and+two
> /page/?filter=one,or,two
>
> I have noticed that Django converts the + to a space
> (request.GET.get('filter') returns one and two), and I´m OK with that. I
> just need to adjust the split() function I use in the View accordingly.

The arguments in a query string are urlencoded. Spaces are urlencoded
as '+'. Django's request.GET is a dict like object with the query
string arguments decoded.

>
> But...
>
> When I try to test this View, and I call:
>
> from django.test import Client
> client = Client()
> client.get('/page/', {'filter': 'one+and+two'})

The test client takes a dictionary of raw strings, not urlencoded
strings. If you like, you are telling it to test the URL
'/page/?filter=one%2Band%2Btwo', as '+' is urlencoded as '%2B'.

Django is consistent, the test client takes raw un-encoded strings,
and request.GET delivers raw un-encoded strings.

Cheers

Tom

-- 
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/CAFHbX1Lt7hvVA3mzR%2BZ4-srnr3pAvuwSDWRfxe_uV%2B%3D5Zoohig%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing Django: testing template at different time

2015-03-18 Thread Zaki Akhmad
On Fri, Mar 13, 2015 at 5:32 AM, Collin Anderson  wrote:
> Hi,
>
> You could try using freezegun to run the test as if it were a certain time
> of day.
> https://pypi.python.org/pypi/freezegun

Hi Collin,

thanks for the response.
After spent some time, finally I managed to get the testing.

I put my code snippets here
https://gist.github.com/za/2a217c47582737f88259

> Or, you could say something like:
> if 9 <= datetime.datetime.now().hour < 17:
> self.assertContains(response, "It's working time!")
> else:
> self.assertContains(response, "Happy holiday!")
>
> That way it will at least not fail (most of the time :).

Yes, but my mentor said it's not best practice in testing because we
want to test all the condition whenever we execute the test code.

-- 
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/CAE7Ck-TX83e9Qt_Xm35rqUzWNBP%2Be_QtE5%3Dicz7_Ydx1-spQuA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing template context processors

2015-03-17 Thread Gergely Polonkai
Hello,

My processor sets some template variables based on request.user and some
DB/redis query results, which are displayed on each page on a header bar,
so I only need to create a mocked request with user set to something
(AnonymousUser or a valid user object).

I'm already using Mock[2] for middleware testing, funny that I didn't think
of this way (especially as I implemented it today), so thanks for pointing
out!

[2] https://pypi.python.org/pypi/mock
On 17 Mar 2015 17:59, "Carl Meyer"  wrote:

> Hi Gergely,
>
> On 03/17/2015 10:52 AM, Gergely Polonkai wrote:
> > I wrote a context processor which makes some global variables of mine
> > available for templates. I cannot find a good (cough… any) article on
> > how to test such processors. Could you give me some directions on where
> > to start with writing one?
>
> Writing a unit test for a context processor is quite simple. Construct a
> fake request (you can use RequestFactory, though if your context
> processor only accesses one or two attributes of the request, it might
> be simpler to just build a custom fake or use a library like pretend
> [1]), then call the context processor function in your test, passing in
> the fake request, and assert that the returned dictionary contains what
> you expect.
>
> If your templates require the values from the context processor in order
> to render correctly, you can also write a higher-level integration or
> functional test by using the test client to access a view that renders a
> template that needs the context processor, and then assert the right
> value is found in the rendered HTML.
>
> Carl
>
>   [1] https://pypi.python.org/pypi/pretend
>
> --
> 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/55085D7A.5040007%40oddbird.net
> .
> 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/CACczBUK0Q%2BriJZ9FNBxDvXAHHUAVNVh8tamCPbqCeQFr__UgTw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing template context processors

2015-03-17 Thread Carl Meyer
Hi Gergely,

On 03/17/2015 10:52 AM, Gergely Polonkai wrote:
> I wrote a context processor which makes some global variables of mine
> available for templates. I cannot find a good (cough… any) article on
> how to test such processors. Could you give me some directions on where
> to start with writing one?

Writing a unit test for a context processor is quite simple. Construct a
fake request (you can use RequestFactory, though if your context
processor only accesses one or two attributes of the request, it might
be simpler to just build a custom fake or use a library like pretend
[1]), then call the context processor function in your test, passing in
the fake request, and assert that the returned dictionary contains what
you expect.

If your templates require the values from the context processor in order
to render correctly, you can also write a higher-level integration or
functional test by using the test client to access a view that renders a
template that needs the context processor, and then assert the right
value is found in the rendered HTML.

Carl

  [1] https://pypi.python.org/pypi/pretend

-- 
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/55085D7A.5040007%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Testing Django: testing template at different time

2015-03-12 Thread Collin Anderson
Hi,

You could try using freezegun to run the test as if it were a certain time 
of day.
https://pypi.python.org/pypi/freezegun

Or, you could say something like:
if 9 <= datetime.datetime.now().hour < 17:
self.assertContains(response, "It's working time!") 
else:
self.assertContains(response, "Happy holiday!")

That way it will at least not fail (most of the time :).

Collin

On Wednesday, March 11, 2015 at 7:43:35 AM UTC-4, Zaki Akhmad wrote:
>
> Hello, 
>
> I'd like to write a test script for my django app. 
>
> Example, if within business hour, my django app will render: 
> "It's working time!" 
>
> And if not within business hour, my django app will render: 
> "Happy holiday!" 
>
> So the views, will check when the url is accessed. 
>
> How do I write the test script? 
> Following django docs here[1], I started to write my test code. 
>
> from django.test import Client, TestCase 
>
> class TestPage(TestCase): 
> def test_holiday(self): 
> response = self.client.get('/day/') 
> self.assertEqual(response.status_code, 200) 
> self.assertContains(response, "It's working time!") 
>
> This test code will success if I run within business hour. But If I 
> run it not within business hour, the test code will fail. 
>
> * How to write a better test code? 
> * How do I use mock/patch? 
> * How to write test code that will check the within and not within 
> business hour in one file that both will success whenever I run the 
> test code? 
>
> [1]
> https://docs.djangoproject.com/en/1.7/topics/testing/tools/#testing-responses 
>
> Thanks, 
>
> -- 
> Zaki Akhmad 
>

-- 
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/3003d453-3d31-4fed-ab9a-eadd40fee8af%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing posts to S3

2015-02-11 Thread Tom Evans
On Wed, Feb 11, 2015 at 7:36 PM, Lee Hinde  wrote:
> I'm using django storages/boto to push json files to s3 where they are to be
> read by a different app.
>
> I'd like to test the file push by using the Test Client to see if the file
> is present on S3.
>
> client = Client()
> r = client.get(url, content_type="application/json")
>
> In every case, r comes back as:
>
> 
>
> I can take the  'url' and paste it into my browser and get the file.
>
> So, there's something about the process I'm not understanding. Is this not
> what Client is intended for?

No, the test client isn't a client for making web requests, it is a
client that creates phony request objects and simulates the
request/response inside of django itself. No network activity will
take place!

Just open it:

try:
r = urllib.urlopen(url).read()
except IOError:
...

Cheers

Tom

-- 
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/CAFHbX1%2BZPVagLTGP9t%3Dpk%2B%3Di7%2BssSu%3DL5T9UO2Y8kEhPwVUkgA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing reusable application: compatible way

2014-12-07 Thread Carl Meyer
On 12/07/2014 12:59 PM, Matwey V. Kornilov wrote:
> The following code works perfect for me, why the code in the
> documentations so sophisticated?
> 
> def runtests():
> os.environ.setdefault("DJANGO_SETTINGS_MODULE",
> "tests.test_settings")
> 
> try:
> from django import setup
> setup()
> except ImportError:
> pass
> from django.core.management import call_command
> 
> call_command("test","tests.__init__")
> 
> if __name__ == "__main__":
> runtests()

Sure, that works too. I don't think it's significantly simpler than the
documented version, and it's less flexible if you want to customize test
running further.

Carl

-- 
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/5484C772.5040505%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Testing reusable application: compatible way

2014-12-07 Thread Carl Meyer
On 12/07/2014 02:28 PM, Carl Meyer wrote:
> On 12/07/2014 08:40 AM, Matwey V. Kornilov wrote:
>> I've followed this documentation:
>> https://docs.djangoproject.com/en/1.7/topics/testing/advanced/#using-the-django-test-runner-to-test-reusable-applications
>> and found that it works only for Django 1.7, whereas I would like to
>> have a code snipped working also for 1.5, 1.6.
>>
>> An issue with the runtests.py from the link above thatdjango.setup() has
>> been introduced only in 1.7 and elder version seems to require different
>> way to prepare settings object.
> 
> Older Django versions didn't require any explicit initialization step,
> so all you need to do is check `hasattr(django, 'setup')` and only call
> it if it exists (or you can check the Django version instead, if you
> prefer).
> 
> DiscoverRunner was only introduced in 1.6, so if you want to be
> 1.5-compatible you'll also need a fallback to the old
> DjangoTestSuiteRunner. And note that the format of test labels changed:
> in DjangoTestSuiteRunner it was an app-label, where in DiscoverRunner
> it's a full Python dotted path.

I forgot that the documented example uses django.test.utils.get_runner
instead of directly importing DiscoverRunner. `get_runner` existed
already in 1.5, so that code should work back to 1.5, I would think.

> You can see an example `runtests.py` that accounts for these differences
> here:
> https://github.com/carljm/django-model-utils/blob/master/runtests.py#L34
> 
> Carl
> 

-- 
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/5484C73B.7020902%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Testing reusable application: compatible way

2014-12-07 Thread Carl Meyer
Hi Matwey,

On 12/07/2014 08:40 AM, Matwey V. Kornilov wrote:
> I've followed this documentation:
> https://docs.djangoproject.com/en/1.7/topics/testing/advanced/#using-the-django-test-runner-to-test-reusable-applications
> and found that it works only for Django 1.7, whereas I would like to
> have a code snipped working also for 1.5, 1.6.
> 
> An issue with the runtests.py from the link above thatdjango.setup() has
> been introduced only in 1.7 and elder version seems to require different
> way to prepare settings object.

Older Django versions didn't require any explicit initialization step,
so all you need to do is check `hasattr(django, 'setup')` and only call
it if it exists (or you can check the Django version instead, if you
prefer).

DiscoverRunner was only introduced in 1.6, so if you want to be
1.5-compatible you'll also need a fallback to the old
DjangoTestSuiteRunner. And note that the format of test labels changed:
in DjangoTestSuiteRunner it was an app-label, where in DiscoverRunner
it's a full Python dotted path.

You can see an example `runtests.py` that accounts for these differences
here:
https://github.com/carljm/django-model-utils/blob/master/runtests.py#L34

Carl

-- 
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/5484C682.1010805%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Testing reusable application: compatible way

2014-12-07 Thread Matwey V. Kornilov

The following code works perfect for me, why the code in the documentations 
so sophisticated?

def runtests():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 
"tests.test_settings")

try:
from django import setup
setup()
except ImportError:
pass
from django.core.management import call_command

call_command("test","tests.__init__")

if __name__ == "__main__":
runtests()


воскресенье, 7 декабря 2014 г., 18:40:42 UTC+3 пользователь Matwey V. 
Kornilov написал:
>
> Hi,
>
> I've followed this documentation: 
> https://docs.djangoproject.com/en/1.7/topics/testing/advanced/#using-the-django-test-runner-to-test-reusable-applications
> and found that it works only for Django 1.7, whereas I would like to have 
> a code snipped working also for 1.5, 1.6.
>
> An issue with the runtests.py from the link above that django.setup() has 
> been introduced only in 1.7 and elder version seems to require different 
> way to prepare settings object.
>

-- 
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/3e14ba33-4d84-4d16-afc0-aa02b6b9ce09%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing equality in template tag

2014-06-26 Thread Tom Evans
On Wed, Jun 25, 2014 at 7:34 PM, Lee Hinde  wrote:
> with view code like so:
>
> import calendar
> months_choices = []
> for i in range(1,13):
> months_choices.append((i, calendar.month_name[i]))
> context['months'] = months_choices
>
>
> and
>
> context['default_month'] = today.month
>
> I have this snippet in a template (my first use of lists like this):
>
> 
> {% for month in months %}
>  value="{{ month.0 }}">
> {{ month.1 }}
> {% endfor %}
> 
>
>
> The issue is the  {% if default_month == month.0 %} always returns false...
> The rest of the select is properly built - I get a number for the value and
> the month name as the label.
>
> Why?
>

Differing types? "1" != 1

Log the repr of both values and see.

Cheers

Tom

PS: Django forms are very good at rendering selects and determining
which one is selected.

-- 
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/CAFHbX1L%2B7USiPBr3LN66AB3ZSFQOc44aqvbu9_6G%3DOwETHEAjw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing equality in template tag

2014-06-26 Thread Roman Klesel
Ugh , sorry of course we know ... forget what i said ...

2014-06-26 9:48 GMT+02:00 Roman Klesel :
> hard to tell since we do not know what values default_month and month.0 have 
> ...
> try to print in the view and examine:
> print type(month[0]), month[0], type(today.month), today.month
>
> 2014-06-25 20:34 GMT+02:00 Lee Hinde :
>> with view code like so:
>>
>> import calendar
>> months_choices = []
>> for i in range(1,13):
>> months_choices.append((i, calendar.month_name[i]))
>> context['months'] = months_choices
>>
>>
>> and
>>
>> context['default_month'] = today.month
>>
>> I have this snippet in a template (my first use of lists like this):
>>
>> 
>> {% for month in months %}
>> > value="{{ month.0 }}">
>> {{ month.1 }}
>> {% endfor %}
>> 
>>
>>
>> The issue is the  {% if default_month == month.0 %} always returns false...
>> The rest of the select is properly built - I get a number for the value and
>> the month name as the label.
>>
>> Why?
>>
>> --
>> 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/CA%2BePoMzx%2B4774Ne21djP-EdSAHDL_64DWhZVQYrUYdND%3DBk2%2Bw%40mail.gmail.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/CAL2Rd%3DKB6MxR22LTYQjVmxiee%2BhktpkqttPmemZQhvm9r9_%3DBA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: testing equality in template tag

2014-06-26 Thread Roman Klesel
hard to tell since we do not know what values default_month and month.0 have ...
try to print in the view and examine:
print type(month[0]), month[0], type(today.month), today.month

2014-06-25 20:34 GMT+02:00 Lee Hinde :
> with view code like so:
>
> import calendar
> months_choices = []
> for i in range(1,13):
> months_choices.append((i, calendar.month_name[i]))
> context['months'] = months_choices
>
>
> and
>
> context['default_month'] = today.month
>
> I have this snippet in a template (my first use of lists like this):
>
> 
> {% for month in months %}
>  value="{{ month.0 }}">
> {{ month.1 }}
> {% endfor %}
> 
>
>
> The issue is the  {% if default_month == month.0 %} always returns false...
> The rest of the select is properly built - I get a number for the value and
> the month name as the label.
>
> Why?
>
> --
> 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/CA%2BePoMzx%2B4774Ne21djP-EdSAHDL_64DWhZVQYrUYdND%3DBk2%2Bw%40mail.gmail.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/CAL2Rd%3DJo__TO_U3OKAeehv4mRzBQEH4nMf0LfNxfoEZB4%2B9j%3Dg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Testing Frameworks and Practices(consensus?)

2013-12-12 Thread Arnold Krille
Am Wed, 11 Dec 2013 12:03:44 -0500
schrieb Thomas Murphy :
> This seems like a more appropriate forum that SO for this discussion.
> 
> I've been testing my apps with Selenium, which seems to be a popular
> choice for Django, but so does unittest and some others, as well as
> using coverage to check for code coverage.
> 
> I'm curious to hear about others experience with testing frameworks,
> particularly those who have moved through more than one about any best
> practices experiences they've had, and what caused the choice to go
> with what you're using now.

We started classically without tests. Then I learned testing through
the excellent tdd-django tutorial. And we started with djangos own
runner (and thus unittest(2)). Unit tests with plain django+unittests,
functional tests with django+selenium. As we encountered some problems
with the test-systems handling of utf-8 in log- and test-messages, we
looked at nose and nose2 as alternative test-runners. Currently we do
use nose2 and are looking at py.test.
Tests are run by developers during development and by jenkins after
checkins. The jenkins runs are with coverage and are finished of by
sonar checking code and results.

So all the current frameworks currently in use by us:
 - Django ;-)
 - nose2
 - selenium
 - jenkins
 - coverage.py
 - sonar

Have fun,

Arnold

-- 
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/20131212155007.2fdbd226%40orinoco.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Testing: @override_settings(AUTH_USER_MODEL='auth.User') no working.

2013-09-30 Thread Serge G. Spaolonzi
Thanks, it worked.
Changing @override_settings(AUTH_USER_MODEL='auth.User') for
@override_settings(AUTH_USER_MODEL='auth.CustomUser') made the trick.

On Sun, Sep 29, 2013 at 9:09 PM, Russell Keith-Magee
 wrote:
>
> On Mon, Sep 30, 2013 at 7:27 AM, Serge G. Spaolonzi 
> wrote:
>>
>> Hi,
>>
>> I am failing to override the AUTH_USER_MODEL settings for a unittest, it
>> throws:
>>
>> "Manager isn't available; User has been swapped for 'None'"
>>
>> Is it possible to override AUTH_USER_MODEL in the unittest?
>> My goal is to use the default user model provided by django for the test
>> only.
>
>
> Yes, it is possible. That's why the approach is documented:
>
> https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-users-and-testing-fixtures
>
> If you're getting an error, It sounds like something else is going wrong in
> your test suite -- my guess would be that you haven't got the auth app in
> INSTALLED_APPS. However, it's impossible to say for sure without seeing more
> code.
>
> Yours,
> Russ Magee %-)
>
> --
> 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.



-- 
Serge G. Spaolonzi
Cobalys Systems
http://www.cobalys.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 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/CA%2BrwjWXc-k166BhY5%3DRRM9LR21MFTyf9KqDMSozKErohbMEchw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Testing: @override_settings(AUTH_USER_MODEL='auth.User') no working.

2013-09-29 Thread Russell Keith-Magee
On Mon, Sep 30, 2013 at 7:27 AM, Serge G. Spaolonzi wrote:

> Hi,
>
> I am failing to override the AUTH_USER_MODEL settings for a unittest, it
> throws:
>
> "Manager isn't available; User has been swapped for 'None'"
>
> Is it possible to override AUTH_USER_MODEL in the unittest?
> My goal is to use the default user model provided by django for the test
> only.
>

Yes, it is possible. That's why the approach is documented:

https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-users-and-testing-fixtures

If you're getting an error, It sounds like something else is going wrong in
your test suite -- my guess would be that you haven't got the auth app in
INSTALLED_APPS. However, it's impossible to say for sure without seeing
more code.

Yours,
Russ Magee %-)

-- 
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: Testing in Django - newbie questions on first test failure and coverage

2013-09-23 Thread Derek
Hi  

Yes, you are right: deleting the _fixture_setup method allows the tests to 
run successfully!  

I also do have all my fixture data stored in 
'appname/fixtures/initial_data.json' so I assume from what you say that 
this data will only be loaded once for all the tests.

Once I have more confidence with further tests, I will also try with 
factoryboy for other, non-fixture, data I need to test.

Thanks again for all the help here.

Derek

On Sunday, 15 September 2013 15:37:35 UTC+2, Derek wrote:
>
> I have an existing Django (1.4) project, with multiple apps and extensive 
> business logic, that I need to write tests for.  Based on a day or two of 
> reading of the core Django docs and numerous blogs (each of which go about 
> things subtly differently!?), I have made a start.  As part of the seeming 
> "best practice" setup, I have also installed django-nose and coverage.
>
> Currently, I have problems with my first test not working and also with 
> coverage seemingly not finding my test. 
>  
> I have a separate `tests` directory in my project, with sub-directories; 
> each corresponding to an app.  Each sub-directory then has a models, views, 
> and functions Python files; acting as placeholders for the test code I 
> think need to write.  In the root of the `tests` directory, I have an 
> __init__.py file that has a number of lines that look like `from 
> myproj.app1.functions import *`.
>
> I have changed the settings.py file to look like this (so that the tests 
> use a "fast" sqlite database):
>
> if 'test' in sys.argv:
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.sqlite3',
> 'NAME': 'test_db'
> }
> }
> else:
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.mysql',
> # etc ... normal setup
>
>
> The first test, in the first functions.py file, looks like this:
>
>
> from django.test import TestCase
> from django.core import management
> from app1.models import default_Property  # function to be tested
>
> def setup():
> management.call_command('loaddata', 'app1/fixtures/initial_data.json', 
> verbosity=1)
>
> def teardown():
> management.call_command('flush', verbosity=1, interactive=False)
>
> class FunctionsTestCase(TestCase):
>
> def _fixture_setup(self):
> pass
>
> def test_default_Property(self):
> self.assertEqual(default_Property(), None)
>
>
> The default_Property() function in app1 is just set to `return None` for 
> now, so that the above test should work.
>
> However, the test fails.  I get this strange error:
>
> ==
> ERROR: test_default_Property (myproj.app1.tests.FunctionsTestCase)
> --
> Traceback (most recent call last):
>   File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", 
> line 508, in __call__
> self._post_teardown()
>   File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", 
> line 522, in _post_teardown
> self._fixture_teardown()
>   File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", 
> line 847, in _fixture_teardown
> transaction.leave_transaction_management(using=db)
>   File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py", 
> line 52, in leave_transaction_management
> connection.leave_transaction_management()
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", 
> line 115, in leave_transaction_management
> raise TransactionManagementError("This code isn't under transaction "
> TransactionManagementError: This code isn't under transaction management
> --
>
> I could not find an obvious solution to this, as I do not even have 
> TransactionMiddleware enabled in my settings.
>
> The other issue relates to coverage - it does not seem to recognise I have 
> written this test and still flags it as `red` ... Currently I am using 
> `coverage html' - but how I get it work properly?
>
> Any help getting started overcoming these issues will be helpful, so I can 
> get on with the actual business of writing tests.  (As a side-note, if 
> there is a good existing code base, for a Django-based project, that has 
> test code I could look at, I'd appreciate a link to it.)
>
> 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 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: Testing in Django - newbie questions on first test failure and coverage

2013-09-23 Thread Derek
Hi Rafael

Yes, you are right: deleting the _fixture_setup method allows the tests to 
run successfully! 

I also do have all my fixture data stored in 
'appname/fixtures/initial_data.json' so I assume from what you say that 
this data will only be loaded once for all the tests.

Once I have more confidence with further tests, I will also try out 
factory_boy for other, non-fixture, data I need to test.

Thanks again for all the help here.

Derek

On Sunday, 22 September 2013 12:40:16 UTC+2, Rafael Durán Castañeda wrote:
>
> Hi,
>
>
> El 21/09/2013, a las 13:36, Derek  
> escribió:
>
> Rafael
>
> I appreciate your reply; below I try and explain further the reasoning 
> behind the approach I took.  If you can respond to that, it would help.
>
>
> Firstly, the issue of test file locations - there are least two places I 
> have found that recommend these be placed in a different directory:
>
> From http://toastdriven.com/blog/2011/apr/17/guide-to-testing-in-django-2/
>
> "I prefer to split up the tests into a file structure that mirrors the 
> app's setup. To do this, we create a new tests directory then move the 
> existing tests.py into tests/views.py."
>
>
> It doesn´t matter if app.tests is a module or a package (some test runners 
> will need tests being importable from app.tests in order to work), so that 
> approach still uses default location as I suggested.
>
> From 
> https://pycon-2012-notes.readthedocs.org/en/latest/testing_and_django.html
>
> "Don’t make the mistake of putting the tests for your app in a tests.py, 
> because then other people who use your app will be forced to run your tests 
> when they don’t really need to. Better to put your tests in another 
> directory."
>
>
> I don´t agree this, since people who don´t want run app.tests can just use 
> a test runner that runs only your tests (as django-nose and pytest-django 
> do); even if you don´t want your tests to be run, you can just exclude them 
> in the setup.py.
>
> So this approach should be OK; and the tests seem work - but with that 
> strange error message.  Still not sure what the exact cause is…
>
>
> Looking further to stackoverflow example, I´ve got the same error as you, 
> but I managed  to solve it just deleting the _fixture_setup method, so my 
> guess was wrong (since there is no conflict with loading/flushing data this 
> way) but  disabling _fixture_setup seems to break Django tests transaction 
> management (tested with Django 1.5).
>
>
> Thanks for the factory_boy suggestion.  I had looked at it, but was trying 
> to avoid having to learn too may things all at once!  The code I have used 
> for loading my fixtures comes from 
> http://stackoverflow.com/questions/979434/how-to-load-fixtures-only-once-in-django-unit-tests
>   
> - and I added that because of the exact problem raised in that question; 
> that Django reloads the fixtures for every single test; and that just seems 
> to slow things right down (we have a lot of fixtures we need for our 
> database).  if you can suggest another or better way to load our fixtures 
> just once for a whole class of tests, I'd appreciate hearing about that.
>
>
> If you need load fixtures just once, you can use initial_data fixture (you 
> can change fixture directories setting in your test settings if you don´t 
> want mess with your production data). However if you need different 
> fixtures to be loaded depending on your test module, your approach may be 
> the right choice; thought you probably want to check django-nose fast 
> fixtures https://github.com/jbalogh/django-nose#enabling-fast-fixtures or 
> just create DB objects programmatically (using factory_boy or whatever).
>
> HTH,
> Rafael
>
>
> Thanks
> Derek
>
>
> On Monday, 16 September 2013 23:20:41 UTC+2, Rafael Durán Castañeda wrote:
>>
>> Hi,
>>
>> Some answers inline and links at the end:
>>
>> 2013/9/15 Derek 
>>
>>> I have an existing Django (1.4) project, with multiple apps and 
>>> extensive business logic, that I need to write tests for.  Based on a day 
>>> or two of reading of the core Django docs and numerous blogs (each of which 
>>> go about things subtly differently!?), I have made a start.  As part of the 
>>> seeming "best practice" setup, I have also installed django-nose and 
>>> coverage.
>>>
>>> Currently, I have problems with my first test not working and also with 
>>> coverage seemingly not finding my test. 
>>>  
>>> I have a separate `tests` directory in my project, with sub-directories; 
>>> each corresponding to an app.  Each sub-directory then has a models, views, 
>>> and functions Python files; acting as placeholders for the test code I 
>>> think need to write.  In the root of the `tests` directory, I have an 
>>> __init__.py file that has a number of lines that look like `from 
>>> myproj.app1.functions import *`.
>>>
>>  
>> Most Django apps. place tests into the app. directory tests 
>> module/package, so I think your layout may cause some 

Re: Testing in Django - newbie questions on first test failure and coverage

2013-09-22 Thread Rafael Durán Castañeda
Hi,


El 21/09/2013, a las 13:36, Derek  escribió:

> Rafael
> 
> I appreciate your reply; below I try and explain further the reasoning behind 
> the approach I took.  If you can respond to that, it would help.
> 
> 
> Firstly, the issue of test file locations - there are least two places I have 
> found that recommend these be placed in a different directory:
> 
> From http://toastdriven.com/blog/2011/apr/17/guide-to-testing-in-django-2/
> 
> "I prefer to split up the tests into a file structure that mirrors the app's 
> setup. To do this, we create a new tests directory then move the existing 
> tests.py into tests/views.py."
> 

It doesn´t matter if app.tests is a module or a package (some test runners will 
need tests being importable from app.tests in order to work), so that approach 
still uses default location as I suggested.

> From 
> https://pycon-2012-notes.readthedocs.org/en/latest/testing_and_django.html
> 
> "Don’t make the mistake of putting the tests for your app in a tests.py, 
> because then other people who use your app will be forced to run your tests 
> when they don’t really need to. Better to put your tests in another 
> directory."
> 

I don´t agree this, since people who don´t want run app.tests can just use a 
test runner that runs only your tests (as django-nose and pytest-django do); 
even if you don´t want your tests to be run, you can just exclude them in the 
setup.py.

> So this approach should be OK; and the tests seem work - but with that 
> strange error message.  Still not sure what the exact cause is…
> 

Looking further to stackoverflow example, I´ve got the same error as you, but I 
managed  to solve it just deleting the _fixture_setup method, so my guess was 
wrong (since there is no conflict with loading/flushing data this way) but  
disabling _fixture_setup seems to break Django tests transaction management 
(tested with Django 1.5).

> 
> Thanks for the factory_boy suggestion.  I had looked at it, but was trying to 
> avoid having to learn too may things all at once!  The code I have used for 
> loading my fixtures comes from 
> http://stackoverflow.com/questions/979434/how-to-load-fixtures-only-once-in-django-unit-tests
>   - and I added that because of the exact problem raised in that question; 
> that Django reloads the fixtures for every single test; and that just seems 
> to slow things right down (we have a lot of fixtures we need for our 
> database).  if you can suggest another or better way to load our fixtures 
> just once for a whole class of tests, I'd appreciate hearing about that.

If you need load fixtures just once, you can use initial_data fixture (you can 
change fixture directories setting in your test settings if you don´t want mess 
with your production data). However if you need different fixtures to be loaded 
depending on your test module, your approach may be the right choice; thought 
you probably want to check django-nose fast fixtures 
https://github.com/jbalogh/django-nose#enabling-fast-fixtures or just create DB 
objects programmatically (using factory_boy or whatever).

HTH,
Rafael

> 
> Thanks
> Derek
> 
> 
> On Monday, 16 September 2013 23:20:41 UTC+2, Rafael Durán Castañeda wrote:
> Hi,
> 
> Some answers inline and links at the end:
> 
> 2013/9/15 Derek 
> I have an existing Django (1.4) project, with multiple apps and extensive 
> business logic, that I need to write tests for.  Based on a day or two of 
> reading of the core Django docs and numerous blogs (each of which go about 
> things subtly differently!?), I have made a start.  As part of the seeming 
> "best practice" setup, I have also installed django-nose and coverage.
> 
> Currently, I have problems with my first test not working and also with 
> coverage seemingly not finding my test. 
>  
> I have a separate `tests` directory in my project, with sub-directories; each 
> corresponding to an app.  Each sub-directory then has a models, views, and 
> functions Python files; acting as placeholders for the test code I think need 
> to write.  In the root of the `tests` directory, I have an __init__.py file 
> that has a number of lines that look like `from myproj.app1.functions import 
> *`.
>  
> Most Django apps. place tests into the app. directory tests module/package, 
> so I think your layout may cause some Django test runner may not able to find 
> your tests. 
> 
> 
> I have changed the settings.py file to look like this (so that the tests use 
> a "fast" sqlite database):
> 
> if 'test' in sys.argv:
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.sqlite3',
> 'NAME': 'test_db'
> }
> }
> else:
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.mysql',
> # etc ... normal setup
> 
> 
> The first test, in the first functions.py file, looks like this:
> 
> 
> from django.test import TestCase
> from django.core import 

Re: Testing in Django - newbie questions on first test failure and coverage

2013-09-21 Thread Derek
Rafael

I appreciate your reply; below I try and explain further the reasoning 
behind the approach I took.  If you can respond to that, it would help.


Firstly, the issue of test file locations - there are least two places I 
have found that recommend these be placed in a different directory:

>From http://toastdriven.com/blog/2011/apr/17/guide-to-testing-in-django-2/

"I prefer to split up the tests into a file structure that mirrors the 
app's setup. To do this, we create a new tests directory then move the 
existing tests.py into tests/views.py."

From 
https://pycon-2012-notes.readthedocs.org/en/latest/testing_and_django.html

"Don’t make the mistake of putting the tests for your app in a tests.py, 
because then other people who use your app will be forced to run your tests 
when they don’t really need to. Better to put your tests in another 
directory."

So this approach should be OK; and the tests seem work - but with that 
strange error message.  Still not sure what the exact cause is...


Thanks for the factory_boy suggestion.  I had looked at it, but was trying 
to avoid having to learn too may things all at once!  The code I have used 
for loading my fixtures comes from 
http://stackoverflow.com/questions/979434/how-to-load-fixtures-only-once-in-django-unit-tests
  
- and I added that because of the exact problem raised in that question; 
that Django reloads the fixtures for every single test; and that just seems 
to slow things right down (we have a lot of fixtures we need for our 
database).  if you can suggest another or better way to load our fixtures 
just once for a whole class of tests, I'd appreciate hearing about that.

Thanks
Derek


On Monday, 16 September 2013 23:20:41 UTC+2, Rafael Durán Castañeda wrote:
>
> Hi,
>
> Some answers inline and links at the end:
>
> 2013/9/15 Derek 
>
>> I have an existing Django (1.4) project, with multiple apps and extensive 
>> business logic, that I need to write tests for.  Based on a day or two of 
>> reading of the core Django docs and numerous blogs (each of which go about 
>> things subtly differently!?), I have made a start.  As part of the seeming 
>> "best practice" setup, I have also installed django-nose and coverage.
>>
>> Currently, I have problems with my first test not working and also with 
>> coverage seemingly not finding my test. 
>>  
>> I have a separate `tests` directory in my project, with sub-directories; 
>> each corresponding to an app.  Each sub-directory then has a models, views, 
>> and functions Python files; acting as placeholders for the test code I 
>> think need to write.  In the root of the `tests` directory, I have an 
>> __init__.py file that has a number of lines that look like `from 
>> myproj.app1.functions import *`.
>>
>  
> Most Django apps. place tests into the app. directory tests 
> module/package, so I think your layout may cause some Django test runner 
> may not able to find your tests. 
>
>
>> I have changed the settings.py file to look like this (so that the tests 
>> use a "fast" sqlite database):
>>
>> if 'test' in sys.argv:
>> DATABASES = {
>> 'default': {
>> 'ENGINE': 'django.db.backends.sqlite3',
>> 'NAME': 'test_db'
>> }
>> }
>> else:
>> DATABASES = {
>> 'default': {
>> 'ENGINE': 'django.db.backends.mysql',
>> # etc ... normal setup
>>
>>
>> The first test, in the first functions.py file, looks like this:
>>
>>
>> from django.test import TestCase
>> from django.core import management
>> from app1.models import default_Property  # function to be tested
>>
>> def setup():
>> management.call_command('loaddata', 
>> 'app1/fixtures/initial_data.json', verbosity=1)
>>
>> def teardown():
>> management.call_command('flush', verbosity=1, interactive=False)
>>
>> class FunctionsTestCase(TestCase):
>>
>> def _fixture_setup(self):
>> pass
>>
>> def test_default_Property(self):
>> self.assertEqual(default_Property(), None)
>>
>>
>>
> Don' t do this! Django provides enough functionality for managing fixtures 
> with ease(see [1]), you don´t need to write custom fixture handling. Even 
> in the case you need more than Django fixtures provides, there are some 
> thirty packages you probably want to look before even thinking about write 
> your own code (I really like factory_boy [2]
> ).
>  
>
>> The default_Property() function in app1 is just set to `return None` for 
>> now, so that the above test should work.
>>
>> However, the test fails.  I get this strange error:
>>
>> ==
>> ERROR: test_default_Property (myproj.app1.tests.FunctionsTestCase)
>> --
>> Traceback (most recent call last):
>>   File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", 
>> line 508, in __call__
>> self._post_teardown()
>>   File 

Re: Testing in Django - newbie questions on first test failure and coverage

2013-09-16 Thread Rafael Durán Castañeda
Hi,

Some answers inline and links at the end:

2013/9/15 Derek 

> I have an existing Django (1.4) project, with multiple apps and extensive
> business logic, that I need to write tests for.  Based on a day or two of
> reading of the core Django docs and numerous blogs (each of which go about
> things subtly differently!?), I have made a start.  As part of the seeming
> "best practice" setup, I have also installed django-nose and coverage.
>
> Currently, I have problems with my first test not working and also with
> coverage seemingly not finding my test.
>
> I have a separate `tests` directory in my project, with sub-directories;
> each corresponding to an app.  Each sub-directory then has a models, views,
> and functions Python files; acting as placeholders for the test code I
> think need to write.  In the root of the `tests` directory, I have an
> __init__.py file that has a number of lines that look like `from
> myproj.app1.functions import *`.
>

Most Django apps. place tests into the app. directory tests module/package,
so I think your layout may cause some Django test runner may not able to
find your tests.


> I have changed the settings.py file to look like this (so that the tests
> use a "fast" sqlite database):
>
> if 'test' in sys.argv:
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.sqlite3',
> 'NAME': 'test_db'
> }
> }
> else:
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.mysql',
> # etc ... normal setup
>
>
> The first test, in the first functions.py file, looks like this:
>
>
> from django.test import TestCase
> from django.core import management
> from app1.models import default_Property  # function to be tested
>
> def setup():
> management.call_command('loaddata', 'app1/fixtures/initial_data.json',
> verbosity=1)
>
> def teardown():
> management.call_command('flush', verbosity=1, interactive=False)
>
> class FunctionsTestCase(TestCase):
>
> def _fixture_setup(self):
> pass
>
> def test_default_Property(self):
> self.assertEqual(default_Property(), None)
>
>
>
Don' t do this! Django provides enough functionality for managing fixtures
with ease(see [1]), you don´t need to write custom fixture handling. Even
in the case you need more than Django fixtures provides, there are some
thirty packages you probably want to look before even thinking about write
your own code (I really like factory_boy [2]
).


> The default_Property() function in app1 is just set to `return None` for
> now, so that the above test should work.
>
> However, the test fails.  I get this strange error:
>
> ==
> ERROR: test_default_Property (myproj.app1.tests.FunctionsTestCase)
> --
> Traceback (most recent call last):
>   File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py",
> line 508, in __call__
> self._post_teardown()
>   File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py",
> line 522, in _post_teardown
> self._fixture_teardown()
>   File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py",
> line 847, in _fixture_teardown
> transaction.leave_transaction_management(using=db)
>   File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py",
> line 52, in leave_transaction_management
> connection.leave_transaction_management()
>   File
> "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py",
> line 115, in leave_transaction_management
> raise TransactionManagementError("This code isn't under transaction "
> TransactionManagementError: This code isn't under transaction management
> --
>
>
Not really sure what´s going with this error, but I think may be related to
your fixtures code and it should disappear if you use Django builtin
fixtures.


> I could not find an obvious solution to this, as I do not even have
> TransactionMiddleware enabled in my settings.
>

Not really sure, but I think Django runs tests under transactions and
loaddata command probably too, so this error might be due to some conflict
with your code.


>
> The other issue relates to coverage - it does not seem to recognise I have
> written this test and still flags it as `red` ... Currently I am using
> `coverage html' - but how I get it work properly?
>
>
How are you running coverage? If you are using django-nose you probably
should use nose coverage plugin.

Any help getting started overcoming these issues will be helpful, so I can
> get on with the actual business of writing tests.  (As a side-note, if
> there is a good existing code base, for a Django-based project, that has
> test code I could look at, I'd appreciate a link to it.)
>
> Thanks
> Derek
>
>  --
> You received this 

Re: Testing Permissions in URL Includes

2013-09-13 Thread Lee Hinde

On Sep 13, 2013, at 12:47 PM, Arnold Krille  wrote:

> On Fri, 13 Sep 2013 11:30:44 -0700 Lee Hinde  wrote:
>> So, the question, is there a way to wrap url include calls in a
>> permission check?
> 
> Wrapping a whole url-include would only work when the url-tree is
> rebuild for each request taking into account the requesting user.
> Todays technologies don't do that anymore.
> 

That helps to understand why it works the way it does. Thanks.

> I would encourage you to look at django-braces and just use the
> PermissionRequiredMixin with your class-based-views.
> 

Doing that now.



> Have fun,
> 

Almost always.

> Arnold

-- 
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: Testing Permissions in URL Includes

2013-09-13 Thread Arnold Krille
On Fri, 13 Sep 2013 11:30:44 -0700 Lee Hinde  wrote:
> So, the question, is there a way to wrap url include calls in a
> permission check?

Wrapping a whole url-include would only work when the url-tree is
rebuild for each request taking into account the requesting user.
Todays technologies don't do that anymore.

I would encourage you to look at django-braces and just use the
PermissionRequiredMixin with your class-based-views.

Have fun,

Arnold


signature.asc
Description: PGP signature


Re: Testing with legacy data

2013-08-06 Thread Tom Evans
On Tue, Aug 6, 2013 at 5:59 AM, Jani Tiainen  wrote:
> Hi,
>
> I've legacy database that is rather large (around 300MB) containing lot more 
> than just data (triggers, stored procedures and such).
>
> Now how I can test with such a data? Preferably I would like to load data to 
> database, run test, rollback changes and run a next test.
>
> But I really wouldn't like to recreate database from the scratch everytime or 
> not to import data every time.
>
> Any suggestions how I could proceed?
>

You want to snapshot the pristine copy of the database, perform your
tests on the database and then roll it back to the snapshot (or copy
the snapshot, do the tests on the snapshot, drop the (altered)
snapshot, re-copy... it's the same effective process).

Theoretically with mysql (and not mysql+InnoDB) you can lock and flush
tables, "FLUSH TABLES WITH READ LOCK", which stops anything from
accessing any data file in mysql's data folder. You can then hotcopy a
database, creating your snapshot.

If your file system is clever, like ZFS (other COW fs are available),
your mysql data directory could be a separate fs, and you can snapshot
and rollback with ease - of course, you must make sure the disk files
are consistent at the point the snapshot is made.

Good luck integrating either of those two options in to tearUp/tearDown.

Cheers

Tom

-- 
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: Testing django views: RequestFactory and CSRF protection

2013-07-20 Thread Vladimir Ignatev
Well, looks like I've found workaround. At first we should test if a view 
have CSRF protection: 
def test_csrf_protected(self):
request = RequestFactory().post('', data={})
response = views.register_form(request)
self.assertEqual(response.status_code, 403)

(fix me, it is very weak test for example purpose)

Then we actually test view, providing request._dont_enforce_csrf_checks = 
True. And voila. Remember that you shouldn't test Django library, so it's 
obsolete to test "CSRF bypassing + view" chain. Test your view only and 
that it is protected with @csrf_protect is absolutely enough.

четверг, 18 июля 2013 г., 11:35:00 UTC+2 пользователь Vladimir Ignatev 
написал:
>
> I need using RequestFactory instead of Client to test one of my views. So 
> the question is how to generate proper CSRF token to provide it to my 
> @csrf_protect'ed view? At this moment I get 403 error when generating POST 
> request. 
> I've read similar topic in this group dated 2011 year, but that topic 
> observed solution of the problem using Client class and it's parameter 
> enforce_csrf. 
>
>

-- 
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.




  1   2   3   >