简体   繁体   English

pytest 方法

[英]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.我坚持如何创建 pytest 来测试我的 class 中的方法是否返回 df。 I know my class functions properly I'm just really new to pytest.我知道我的 class 功能正常我只是 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

@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.我一直在阅读文档,但我不知道如何链接固定装置以使方法执行,以便我可以检查它是否返回了 df,然后我可以检查 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.如果您使用的是 pytest 夹具,这些需要在您打算使用这些夹具的测试 function 中用作 arguments。 They will not automatically be accessible within your test function.它们不会在您的测试 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 ============================================================================================

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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