简体   繁体   中英

pytest for a method

I'm stuck on how to create a pytest to test if a method in a class of mine returns a df. I know my class functions properly I'm just really new to pytest.

the method

def interest_over_time(self, kw_list, start_date, end_date):
        """The method which uses the widget and cookies to return
        a dataframe containing integer values.

        Args:
            kw_list: A list of keywords for the request,
                no more than 1 total for a clean df,
                no more than 5 or the request will fail.
            start_date: A string for initial start date
                formated as YYYY-MM-DDTHH.
                Must be passed as T value for the time from 00-23
            end_date: A string for initial start date
                formated as YYYY-MM-DDTHH.
                Must be passed as T value for the time from 00-23

        Returns:
            A DataFrame which containes structed columns with data,
            time and int value from the data
            which is in the Interest Over Time section of Google Trends.
            For example:

                 formattedTime formattedAxisTime value hasData formattedValue
        date
        Jun 4, 2020 at 7:00 PM           7:00 PM  [75]  [True]           [75]
        Jun 4, 2020 at 7:01 PM           7:01 PM  [71]  [True]           [71]
        Jun 4, 2020 at 7:02 PM           7:02 PM  [73]  [True]           [73]
        Jun 4, 2020 at 7:03 PM           7:03 PM  [66]  [True]           [66]
        Jun 4, 2020 at 7:04 PM           7:04 PM  [76]  [True]           [76]

        """

        self._dict_request(kw_list, start_date, end_date)
        self._get_widget()

        over_time_req_payload = {
            'req': json.dumps(self.interest_over_time_widget['request']),
            'token': self.interest_over_time_widget['token'],
            'tz': self.timezone
        }

        response = requests.get(self.INTEREST_OVER_TIME_URL,
                                params=over_time_req_payload,
                                cookies=self.cookies,
                                headers={'accept-language': 'us'})

        if response.status_code == 200:
            req_trimmed = response.text[5:]
            req_dict = json.loads(req_trimmed)
            df = pd.DataFrame(req_dict['default']['timelineData'])
            df['date'] = pd.to_datetime(df['time'].astype(dtype='float64'),
                                        unit='s')
            df = df.set_index(['date']).sort_index()
            return df

        else:
            raise BaseException(
                'The request failed: Google returned a '
                'response with code {0}.'.format(response.status_code)
            )

what I have so far with the pytest

@pytest.fixture
def keyword():
    return ['bitcoin']


@pytest.fixture
def start():
    return '2020-06-05T01'


@pytest.fixture
def end():
    return '2020-06-05T04'

def test_request():
    """test the dict functionality"""
    pytrends = GoogleTrends()
    assert pytrends.interest_over_time(kw_list=keyword, start_date=start, end_date=end)

I'm pretty sure that is how I have to pass the parameters to the method. I've been reading the documentation, but I can't figure out how to chain the fixtures to make the method execute, so that I can check if it returned a df, and then I can check the columns of the df. The examples I can find only aren't really useful.

Any help is appreciated.

If you are using pytest fixtures, these need to be used as arguments in the test function you intend using these fixtures. They will not automatically be accessible within your test function.

Here is a minimal working example:

some_module.py:

def some_function(*args):
    return list(args)

test_some_module.py:

import pytest

import some_module

@pytest.fixture
def keyword():
    return ['bitcoin']


@pytest.fixture
def start():
    return '2020-06-05T01'


@pytest.fixture
def end():
    return '2020-06-05T04'

def test_request(keyword, start, end):
    """test the dict functionality"""
    assert some_module.some_function(keyword, start, end) == [keyword, start, end]

when I run this test i will get a passed test:

❯ pytest
========================================================================================== test session starts ===========================================================================================
platform linux -- Python 3.8.10, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /home/user/some_package
collected 1 item

test_some_module.py .                                                                                                                                                                              [100%]

=========================================================================================== 1 passed in 0.00s ============================================================================================

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM