标签: python-unittest

是否有与“unittest.TestCase.fail()”相反的方法来通过Python单元测试?

我目前正在使用它self.assertTrue(True)来通过测试。我想要的是如果出现特定警告则通过测试。

import warnings
class test(unittest.TestCase):
    def test_1(self):
        with warning.catch_warnings(record=False):
            warning.simplefilter("error", category=CustomWarning)
            try: function_that_raisesCustomWarning()
            except CustomWarning as w: self.assertTrue(True)
Run Code Online (Sandbox Code Playgroud)

python warnings unit-testing python-unittest

5
推荐指数
1
解决办法
1075
查看次数

python 中的 aws lambda 函数的自动化测试

我有一个 aws lambda 函数,它将在 dynamodb 中为 s3 存储桶中创建的每个对象写入 s3 文件元数据信息,为此我在 s3 存储桶上有事件触发器。所以我计划使用 python 进行自动化测试。任何人都可以帮助我如何自动化此 lambda 函数以使用 unittest 包测试以下内容。

  1. 验证 dynamodb 表是否存在
  2. 验证s3中是否存在bucket以进行事件触发。
  3. 验证 s3 存储桶中的文件计数和 Dynamodb 表中的记录计数。

python automated-tests python-unittest aws-lambda

5
推荐指数
1
解决办法
2932
查看次数

MagicMock 和包装

为什么“wraps”关键字对于 MagicMock 对象的作用不一致?普通方法会传递到包装对象,但不会传递“特殊”方法。在下面的测试中,第一个断言通过,第二个断言失败。

import mock
import unittest


class Foo(object):
    def bar(self):
        return 1

    def __len__(self):
        return 3


class TestWrap(unittest.TestCase):
    def test(self):
        foo = Foo()
        c = mock.MagicMock(wraps=foo)
        assert c.bar() == 1 # Passes
        assert len(c) == 3 # Fails
Run Code Online (Sandbox Code Playgroud)

我在文档中找不到任何表明这一点的内容。我错过了什么吗?

python mocking python-unittest magicmock

5
推荐指数
1
解决办法
3700
查看次数

在应用程序上下文之外工作;FlaskClient 对象没有属性“app_context”

我们FlaskClient object has no attribute 'app_context'通过这个测试得到:

应用程序.py:

import logging
from logging.handlers import RotatingFileHandler

from blueprints import default, otherstuff
from global_vars import app, db


def generate_app():
    app.config.from_object('config.flask_config')
    db.init_app(app)


   # registering blueprints
    app.register_blueprint(default.default)
    app.before_request(oauth_package.authenticate_all_requests)
    return app

if __name__ == '__main__':
    flask_app = generate_app()
    flask_app.run(port=5002, debug=True)
Run Code Online (Sandbox Code Playgroud)

测试文件.py:

import unittest
import mock
from starter_file import generate_app
import flask
import blueprints


class TestBase(unittest.TestCase):

    def setUp(self):
        # creates a test client
        app = generate_app()
        app.testing = True
        self.app = app.test_client()
        # propagate the exceptions …
Run Code Online (Sandbox Code Playgroud)

python unit-testing flask python-unittest

5
推荐指数
1
解决办法
6152
查看次数

Python:单元测试检查不同位置的对象是否相同?

解释这一点的最简单方法:

import unittest
from element import Element

class TestHTMLGen(unittest.TestCase):

    def test_Element(self):
        page = Element("html", el_id=False)
        self.assertEqual(page, Element("html", el_id=False))  # this is where I need help
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

AssertionError: <element.Element object at 0x025C1B70> != <element.Element object at 0x025C1CB0>
Run Code Online (Sandbox Code Playgroud)

我知道这些对象并不完全相同,但是有什么方法可以检查它们是否相等?我认为assertEqual 会起作用。

编辑:我正在使用 addTypeEqualityFunc。但是,我仍然遇到麻烦

def test_Element(self):
    page = Element("html", el_id=False)
    self.addTypeEqualityFunc(Element, self.are_elements_equal)
    self.assertEqual(page, Element("html", el_id=False))

def are_elements_equal(self, first_element, second_element, msg=None):
    print first_element.attribute == second_element.attribute
    return type(first_element) is type(second_element) and first_element.tag == second_element.tag and first_element.attribute == second_element.attribute
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:False,它表示测试通过了。它不应通过,因为first_element.attribute 不等于second_element.attribute。此外,即使我只有return falsefor are_elements_equal,测试仍然通过。

python unit-testing python-unittest

5
推荐指数
1
解决办法
5667
查看次数

如何在我的测试代码上运行 mypy?

我有一个项目,其中只有验收测试代码是 Python,我想确保我已正确键入注释。目前测试运行如下:

python -m unittest discover test
Run Code Online (Sandbox Code Playgroud)

有没有某种方法可以集成mypy到该命令中而不需要太多更改?我不想运行两次测试。我必须重写unittest.TestLoader才能执行此操作吗?

或者,mypy确实支持使用-m/运行模块--module,但mypy --module=unittest discover test失败

mypy: 错误:只能指定以下之一:模块、包、文件或命令。

有没有办法将模块参数传递给mypy

python python-3.x python-unittest mypy

5
推荐指数
1
解决办法
7015
查看次数

Python 单元测试任务.apply_async()

使用覆盖率来查看需要测试的内容,覆盖率显示接下来必须进行测试: send_alert.apply_async()

我知道这是芹菜任务,但是有什么方法可以测试代码行吗?

其余代码用于理解测试逻辑:

class SomeView(GenericAPIView)
    def post(self, request, *args, **kwargs):
        #some code
        if not value:
           send_alert.apply_async()
           # response
        # not if Response
Run Code Online (Sandbox Code Playgroud)

由于第一个答案而编写的测试

    @patch('event.views.send_alert')
    def test_send_alert(self, mock_send):
        data = {some data for post}
        response = self.client.post('/api/{0}/mettings/'.format(self.user), data)
        print(response.json())
        self.assertTrue(mock_send.called)
Run Code Online (Sandbox Code Playgroud)

我还检查了任务完成后的情况,print('Tasks Passed')我看到任务已通过的消息,但测试失败并出现错误AssertionError: False is not true

python django-testing celery python-unittest django-tests

5
推荐指数
1
解决办法
2269
查看次数

嘲笑雪花连接

我在 python 中有一个 SnowflakeApi 类,它只是作为 SnowflakeConnection 类之上的包装器。我的 SnowflakeApi 是

import logging
import os
from snowflake.connector import connect    

class SnowflakeApi(object):
    """
    Wrapper to handle snowflake connection
    """

    def __init__(self, account, warehouse, database, user, pwd):
        """
        Handles snowflake connection. Connection must be closed once it is no longer needed
        :param account:
        :param warehouse:
        :param database:
        """
        self.__acct = self._account_url(account)
        self.__wh = warehouse
        self.__db = database
        self.__connection = None
        self.__user = user
        self.__pwd = pwd

    def __create_connection(self):

        try:
            # set the proxy here …
Run Code Online (Sandbox Code Playgroud)

pytest python-unittest python-unittest.mock snowflake-cloud-data-platform

5
推荐指数
2
解决办法
1万
查看次数

如何测试 google Drive API python 客户端

目前,我的 django 项目中有一个 google Drive API 客户端,可以按预期工作。

import unittest
from unittest import mock

DRIVE_API_VERSION = "v3"
DRIVE_API_SERVICE_NAME = "drive"
DRIVE_AUTHORIZED_USER_FILE = "path/to/secrets/json/file"
DRIVE_SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file ', 'https://www.googleapis.com/auth/drive.appdata']

def construct_drive_service():
    try:
        drive_credentials = google.oauth2.credentials.Credentials.from_authorized_user_file(
            DRIVE_AUTHORIZED_USER_FILE, scopes=DRIVE_SCOPES)
    except FileNotFoundError:
        print('Drive credentials not created')
        pass
    if drive_credentials:
        return build(DRIVE_API_SERVICE_NAME, DRIVE_API_VERSION, credentials=drive_credentials, cache_discovery=False)
    else:
        return None
Run Code Online (Sandbox Code Playgroud)

现在我面临的挑战是为这个函数编写测试。但我不知道该使用什么策略。我试过这个

class TestAPICalls(unittest.TestCase):

    @mock.patch('api_calls.google.oauth2.credentials', autospec=True)
    def setUp(self, mocked_drive_cred):
        self.mocked_drive_cred = mocked_drive_cred

    @mock.patch('api_calls.DRIVE_AUTHORIZED_USER_FILE')
    def test_drive_service_creation(self, mocked_file):
        mocked_file.return_value = "some/file.json"
        self.mocked_drive_cred.Credentials.return_value = mock.sentinel.Credentials
        construct_drive_service()
        self.mocked_drive_cred.Credentials.from_authorized_user_file.assert_called_with(mocked_file)
Run Code Online (Sandbox Code Playgroud)

但我的测试失败并出现以下错误

    with io.open(filename, 'r', …
Run Code Online (Sandbox Code Playgroud)

python-3.x google-drive-realtime-api python-unittest

5
推荐指数
0
解决办法
1419
查看次数

在 Python 中使用 Mock 来实现嵌套对象(DynamoDB 和表)

我想使用来自 DynamoDb 的不同输入来测试函数的行为。有两种主要行为:当在表中找到搜索关键字时和当未在表中找到搜索关键字时。这是该函数的最小代码:

import boto3
from boto3.dynamodb.conditions import Key

def main(symbol):
   dynamo = boto3.resource("dynamodb")
   table = dynamo.Table("mytable")
   data = table.query(KeyConditionExpression=Key("symbol").eq(symbol))

   if data.count > 0:
      # result = some_output
   else:
      result = {'status': '404'}
   return result
Run Code Online (Sandbox Code Playgroud)

我想通过发送空结果和非空项目列表来通过单元测试来测试此代码,大致如下:

import boto3
import unittest
from unittest.mock import Mock, patch

class TestMainHandler(unittest.TestCase): 
   ...
   def test_main_fails_on_wrong_symbol(self):
       with patch.object(main_handler, 'table') as get_mock:
          get_mock.return_value = []
          result = main('dummy_symbol')
          expect_result = {'status': '404'}
   self.assertEqual(result, expect_result)
Run Code Online (Sandbox Code Playgroud)

但我无法运行模拟部分。我想知道您是否可以指导我如何模拟嵌套表和发电机变量。我非常感谢您的善意帮助。

python mocking python-unittest

5
推荐指数
1
解决办法
8737
查看次数