2

Why does Pytest return the collection error "In test_billing_month_year: function uses no argument 'date" even though date is used and defined?

The function billing_month_year() simply returns the previous month and year of the current date.

import datetime as dt
import pytest 
from mock import patch

def billing_month_year():
    today = dt.datetime.utcnow()
    #last month from current date
    last_month = today.month - 1 if today.month>1 else 12
    #last year from current date
    last_month_year = today.year if today.month > last_month else today.year - 1
    return last_month, last_month_year

@pytest.mark.parametrize(
    'date, expected',
    [
        #last month in previous year
        (dt.datetime(year=2020, month=1, day=21), (12, 2019)),
        #last month in current year
        (dt.datetime(year=2020, month=2, day=21), (01, 2020)),
    ]
)
@patch('dt.datetime.utcnow')
def test_billing_month_year(date, expected, mock_utcnow):
    mock_utcnow.return_value = date
    test = billing_month_year()
    assert test == expected

Tamdim
  • 972
  • 2
  • 12
  • 29

1 Answers1

5

Decorators are always applied in the reverse order they are added, e.g. in this case first the patch decorator and then the pytest.mark.parametrize decorator is applied. This means that the arguments shall be in the respective order:

@pytest.mark.parametrize(
    'date, expected',
    [
        (dt.datetime(year=2020, month=1, day=21), (12, 2019)),
        (dt.datetime(year=2020, month=2, day=21), (01, 2020)),
    ]
)
@patch('dt.datetime.utcnow')
def test_billing_month_year(mock_utcnow, date, expected):
    mock_utcnow.return_value = date
    test = billing_month_year()
    assert test == expected

The patching probably won't work either, see answers to this question for solutions to this.

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46
  • This worked thanks. As pointed out, patching datetimes does not work since python built in type are immutable. I was able to get around by using the [freezetime](https://github.com/spulec/freezegun) and [forbiddenfruit](https://github.com/clarete/forbiddenfruit) libraries. – Tamdim Mar 16 '20 at 21:28