1

I was doing the following for a Django form definition (embarrassing, yes):

class DealAdvancedSearchForm(forms.Form): weekday_choices = [ ['monday', 'Monday'], ['tuesday', 'Tuesday'], ['wednesday', 'Wednesday'], ['thursday', 'Thursday'], ['friday', 'Friday'], ['saturday', 'Saturday'], ['sunday', 'Sunday'], ] weekday_index = date.today().weekday() weekday_choices[weekday_index][1] += ' (Today)' weekday_choices[weekday_index+1][1] += ' (Tomorrow)' weekday = forms.ChoiceField(label='Day of the week', choices=weekday_choices, required=False) 

As you probably guessed by now, this works fine as long as date.today() does not change. All my tests passed. However, once the date changes, it is incorrectly keeping initial date's choice marked as today.

I have since figured out how dumb this was and have moved the code into the __init__ method.

Now I want to write a test for it. Does anyone know how would I test that the correct weekday is marked as (Today) when the date changes?

1 Answer 1

1

Index out of bounds error:

Watch out for [weekday_index+1] for 'sunday', use [(weekday_index+1)%7] to wrap down to 0. 

Extract the choices into a method to make it easy to test. If the method only contains python and no django, it will be easier to test and thus easier to understand. I also agree that you should create an __init__, today can change at the the end of today and needs to vary with that.

def weekday_choices(self, todays_index): ... return choices_list 

EDIT:

  • Currently your code runs exactly once.
  • Move the logic to operate on an instance instead of at the class level.
  • Use a library like MiniMock to mock responses from date.today().weekday().
    • date.today() will need to return a mock that will use returns_iter.
  • Instanciate 2 forms and assert that their choices lists are as expected.
    • One for today's date, one for tomorrow.
  • You can mock for the modulo test too.
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the modulus suggestion. However, what I want is to test what will happen if the date changes.
@NimmyLebby, I added some info on MiniMock. A very useful tool to help with testing.
I cannot +1 again but I'm going to dive into this tomorrow night. Sounds like solid suggestions. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.