天道酬勤,学无止境

python-unittest

How to mock a property

问题 我在问如何使用 Python 3 在单元测试中模拟类属性。我尝试了以下方法,这对我遵循文档很有意义,但它不起作用: foo.py: class Foo(): @property def bar(self): return 'foobar' def test_foo_bar(mocker): foo = Foo() mocker.patch.object(foo, 'bar', new_callable=mocker.PropertyMock) print(foo.bar) 我已经安装了pytest和pytest_mock并像这样运行测试: pytest foo.py 我收到以下错误: > setattr(self.target, self.attribute, new_attr) E AttributeError: can't set attribute /usr/lib/python3.5/unittest/mock.py:1312: AttributeError 我的期望是测试运行没有错误。 回答1 属性机制依赖于在对象的类上定义的属性属性。 您不能在类的单个实例上创建“类似属性”的方法或属性(为了更好地理解,请阅读 Python 的描述符协议) 因此,您必须将补丁应用到您的类 - 您可以使用with语句,以便在测试后正确恢复该类: def test_foo_bar

2022-07-11 09:58:03    分类:技术分享    python   python-3.x   pytest   python-unittest   python-mock

Testing abstract classes in Python [duplicate]

问题 这个问题在这里已经有了答案: Python - 测试抽象基类6 个答案 5年前关闭。 考虑以下场景。 import six from abc import ABCMeta, abstractmethod class ThisIsAnAbstractClass(six.with_metaclass(ABCMeta)): @abstractmethod def __init__(self,parameter): self.parameter = parameter def do_something(): """do something""" 有一个类扩展形式 ABCMeta(一个抽象类),其中包含一个抽象方法。 由于该抽象init () 方法,无法初始化此类。 有没有办法测试这个类? (至少使用任何测试框架) 回答1 创建抽象类的子类,然后测试子类。 from abc import ABCMeta, abstractmethod class ThisIsAnAbstractClass(object): __metaclass__ = ABCMeta # <-- @abstractmethod def __init__(self, parameter): self.parameter = parameter def do_something(): """do something""

2022-05-06 10:01:05    分类:技术分享    python   unit-testing   python-2.7   nosetests   python-unittest

How to test SQLAlchemy with reflected database

As my flask app should not write anything in my database, I set up Flask-SQLAlchemy to reflect my database. This way I do not have to change my models, when I change my schema: # app/__init__.py from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(): app = Flask(__name__) db.init_app(app) with app.app_context(): db.Model.metadata.reflect(db.engine) # app/models.py from app import db class Data(db.Model): __table__ = db.Model.metadata.tables['data'] This all works fine and dandy. But now, I wanted to implement tests using unittest. But I could not

2022-05-03 01:00:22    分类:问答    sqlalchemy   flask-sqlalchemy   python-unittest   flask-testing

VSCode 1.39.x & Python 3.7.x: "ImportError: attempted relative import with no known parent package" - when started without debugging (CTRL+F5))

when running Python test from withing VS Code using CTRL+F5 I'm getting error message ImportError: attempted relative import with no known parent package when running Python test from VS Code terminal by using command line python test_HelloWorld.py I'm getting error message ValueError: attempted relative import beyong top-level package Here is the project structure How to solve the subject issue(s) with minimal (code/project structure) change efforts? TIA! [Update] I have got the following solution using sys.path correction: import sys from pathlib import Path sys.path[0] = str(Path(sys.path[0

2022-05-02 06:47:27    分类:问答    python   import   visual-studio-code   package   python-unittest

Difference between using unit test and doing tests normally in Python3

What is actually the difference between using unit tests and normal tests? By normal tests I mean, using the if statement for example to determine if the calculation is equal to the desired answer if it returns false, we can raise AssertionError

2022-05-02 03:44:39    分类:问答    python   python-3.x   unit-testing   python-unittest

Mocking method pandas.read_excel does not work with @patch Python

I'm writing unit tests with Python for a project and recently encountered a problem with the decorator @patch. I have the following method which I need to test def _read_from_disk(self, excel_kwargs): """ Read excel file from disk and apply excel_kwargs. Args: excel_kwargs: Parameters for pandas.read_excel. Returns: DataFrame or dict of DataFrames. """ return pd.read_excel(self.location, **excel_kwargs) My test method structure is @patch("program.data.excel.BaseExcelReader._read_from_disk.pd.read_excel") def test___read_from_disk(self, mock_df): mock_df.return_value = pd.DataFrame({"test_id":

2022-05-01 22:48:42    分类:问答    python   unit-testing   mocking   python-unittest   patch

flask validate_on_submit() returns false even when WTF_CSRF_ENABLED is set to False (unittest-ing)

Giving the necessary code below. The post request that I'm doing in my test_book_creation() is supposed to create a Book record which it is not doing because the validate_on_submit() is returning False even when I've set WTF_CSRF_ENABLED app config variable to False. config object: class TestConfig: TESTING = True WTF_CSRF_ENABLED = False DEBUG = False SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_SQLALCHEMY_DATABASE_URI') test function: def test_book_creation(self): data = dict(book_count=2, title='A Book for Testing', author='tester',\ price=340

2022-05-01 21:25:35    分类:问答    flask   http-post   flask-sqlalchemy   python-unittest   flask-wtforms

Proper way to return mocked object using pytest.fixture

I'm trying to setup the target under test in @pytest.fixture and use it in all my tests in the module. I'm able to patch the test correctly, but after I add the @pytest.fixture to return the mock object and invoke the mocked object in other unit tests the object starting to refer back to the original function. Following is the code I have. I was expecting the mocked_worker in the unit test to refer to the return value, but it is invoking the actual os.getcwd method instead. Please help me correct the code: import os import pytest from unittest.mock import patch class Worker: def work_on(self)

2022-05-01 18:00:58    分类:问答    python   python-3.x   unit-testing   pytest   python-unittest

selenium.common.exceptions.WebDriverException: Message: no such session while executing testcases through Python unittest module

import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys class KenLogin(unittest.TestCase): def test_globe(self): global driver driver = webdriver.Chrome(executable_path='E:\Learning\chromedriver.exe') driver.maximize_window() def test_login(self): driver.implicitly_wait(2000) driver.get("http://qa.kenzen.com") username = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[2]/form/div[1]/input") password = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[2]/form/div[2]/input") username.send_keys("pardeepk@clovity.com")

2022-04-30 08:25:41    分类:问答    python   google-chrome   selenium-webdriver   selenium-chromedriver   python-unittest

Failed to navigate to https://www.google.ca. This usually means that a call to the COM method IWebBrowser2::Navigate2() with Python Unittest Selenium

from selenium import webdriver import unittest from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from time import sleep class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.driver = webdriver.Ie(executable_path="C:\\webdriver\\IEDriverServer.exe") self.driver.maximize_window() self.driver.get("https://www.google.ca") def test_googletest(self): element = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.NAME, "q"))) element.send_keys("System")

2022-04-28 13:24:33    分类:问答    python   selenium   internet-explorer-11   python-unittest   selenium-iedriver