Hướng dẫn mock directory python - thư mục giả python

Khung chế nhạo tiêu chuẩn trong Python 3.3+ là unittest.mock; Bạn có thể sử dụng điều này cho hệ thống tập tin hoặc bất cứ điều gì khác.

Bạn cũng có thể chỉ cần cuộn nó bằng cách chế giễu thông qua việc vá khỉ:

Một ví dụ tầm thường:

import os.path
os.path.isfile = lambda path: path == '/path/to/testfile'

Đầy đủ hơn một chút (chưa được kiểm tra):

import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 

Trong ví dụ này, các chế giễu thực tế là tầm thường, nhưng bạn có thể sao lưu chúng với một cái gì đó có trạng thái để có thể đại diện cho các hành động hệ thống tập tin, chẳng hạn như lưu và xóa. Có, đây là tất cả một chút xấu xí vì nó đòi hỏi phải sao chép/mô phỏng hệ thống tập tin cơ bản trong mã.

Lưu ý rằng bạn không thể khỉ python tích hợp. Điều đó đang được nói ...

Đối với các phiên bản trước, nếu có thể sử dụng thư viện của bên thứ ba, tôi sẽ đi cùng với sự tuyệt vời của Michael Foord, hiện là

import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
9 trong thư viện tiêu chuẩn kể từ 3.3+ nhờ PEP 0417, và bạn có thể nhận nó trên PYPI cho Python 2.5 +. Và, nó có thể chế giễu xây dựng!

Bạn có thể tạo một trình quản lý bối cảnh tạo và xóa tệp.

from contextlib
import contextmanager

@contextmanager
def mock_file(filepath, content = ''):
   with open(filepath, 'w') as f:
   f.write(content)
yield filepath
try:
os.remove(filepath)
except Exception:
   pass

def test_function():
   with mock_file(r '/dirname/filename.txt'):
   function()

Gợi ý: 2

Unittest.mock là một thư viện để thử nghiệm trong Python. Nó cho phép bạn thay thế các phần trong hệ thống của bạn được kiểm tra bằng các đối tượng giả và đưa ra các xác nhận về cách chúng đã được sử dụng., Các đối tượng yêu cầu không thể gọi được, vì vậy giá trị trả về của việc khởi tạo yêu cầu bị chế giễu của chúng tôi. Với thông số kỹ thuật tại chỗ, bất kỳ lỗi chính tả nào trong các khẳng định của chúng tôi sẽ nêu ra lỗi chính xác:,, nếu một phiên bản giả có tên hoặc thông số kỹ thuật được gán cho một thuộc tính, nó đã giành được trong chuỗi niêm phong. Điều này cho phép người ta ngăn chặn con dấu sửa một phần của đối tượng giả.

>>> from unittest.mock
import MagicMock
   >>>
   thing = ProductionClass() >>>
   thing.method = MagicMock(return_value = 3) >>>
   thing.method(3, 4, 5, key = 'value')
3
   >>>
   thing.method.assert_called_with(3, 4, 5, key = 'value')
>>> mock = Mock(side_effect = KeyError('foo')) >>>
   mock()
Traceback(most recent call last):
   ...
   KeyError: 'foo'
>>> values = {
      'a': 1,
      'b': 2,
      'c': 3
   } >>>
   def side_effect(arg):
   ...
   return values[arg]
      ...
      >>>
      mock.side_effect = side_effect >>>
      mock('a'), mock('b'), mock('c')
      (1, 2, 3) >>>
      mock.side_effect = [5, 4, 3, 2, 1] >>>
      mock(), mock(), mock()
      (5, 4, 3)
>>> from unittest.mock
import patch
   >>>
   @patch('module.ClassName2')
   [email protected]patch('module.ClassName1')
   ...def test(MockClass1, MockClass2):
   ...module.ClassName1()
   ...module.ClassName2()
   ...assert MockClass1 is module.ClassName1
   ...assert MockClass2 is module.ClassName2
   ...assert MockClass1.called
   ...assert MockClass2.called
   ...
   >>>
   test()
>>> with patch.object(ProductionClass, 'method', return_value = None) as mock_method:
   ...thing = ProductionClass()
   ...thing.method(1, 2, 3)
   ...
   >>>
   mock_method.assert_called_once_with(1, 2, 3)
>>> foo = {
      'key': 'value'
   } >>>
   original = foo.copy() >>>
   with patch.dict(foo, {
      'newkey': 'newvalue'
   }, clear = True):
   ...assert foo == {
      'newkey': 'newvalue'
   }
   ...
   >>>
   assert foo == original

Gợi ý: 3

Việc chế giễu mô phỏng sự tồn tại và hành vi của một đối tượng thực, cho phép các kỹ sư phần mềm kiểm tra mã trong các kịch bản giả thuyết khác nhau mà không cần phải dùng đến vô số cuộc gọi hệ thống. Do đó, việc chế giễu có thể cải thiện đáng kể tốc độ và hiệu quả của các bài kiểm tra đơn vị. Vì bản vá vào SYS là bản vá ngoài cùng, nó sẽ được thực thi cuối cùng, làm cho nó trở thành tham số cuối cùng trong các đối số phương thức kiểm tra thực tế. Hãy lưu ý về điều này và sử dụng trình gỡ lỗi khi chạy các bài kiểm tra của bạn để đảm bảo rằng các tham số phù hợp đang được tiêm đúng thứ tự., Chúng tôi sẽ bắt đầu với một phương thức RM vào một lớp dịch vụ. Thực sự có một nhu cầu chính đáng, mỗi lần, để gói gọn một chức năng đơn giản như vậy thành một đối tượng, nhưng ít nhất nó sẽ giúp chúng tôi chứng minh các khái niệm chính trong chế giễu. Hãy để Let Refactor:

Tất cả chúng ta cần phải xóa các tệp khỏi hệ thống tập tin của mình theo thời gian, vì vậy hãy để viết một chức năng trong Python, điều này sẽ giúp các tập lệnh của chúng ta dễ dàng hơn một chút.

import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
0

Hãy để viết một trường hợp thử nghiệm truyền thống, tức là không có giả:

import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
0

Hãy để tái cấu trúc trường hợp thử nghiệm của chúng tôi bằng cách sử dụng

from contextlib
import contextmanager

@contextmanager
def mock_file(filepath, content = ''):
   with open(filepath, 'w') as f:
   f.write(content)
yield filepath
try:
os.remove(filepath)
except Exception:
   pass

def test_function():
   with mock_file(r '/dirname/filename.txt'):
   function()
0:
import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
1

Gợi ý: 4

Một trong các tệp yêu cầu một tệp cụ thể để tồn tại. (ví dụ: "/dir_name/file_name.txt") nếu không nó sẽ gây ra lỗi. Khi viết các bài kiểm tra đơn vị cho mã Python, làm thế nào tôi có thể chế giễu sự tồn tại của tệp ?, 4 ngày trước ngày 08 tháng 7 năm 2019 & nbsp; · Dán mã trên vào tệp Python mới và chạy nó. Có nhiều quy ước đặt tên khác nhau cho các tệp kiểm tra đơn vị, nhưng tôi khuyên dùng quy ước của Test_.py. Ví dụ, tôi sẽ đặt tên ...

import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
2

Gợi ý: 5

Mở tệp trong muối được thực hiện bằng Salt.utils.files.fopen (). Khi kiểm tra mã đọc từ các tệp, người trợ giúp mock_open có thể được sử dụng để chế giễu FileHandles. Lưu ý rằng không giống mock_open như unittest.mock.mock_open () từ thư viện tiêu chuẩn Python, mà là một triển khai riêng biệt có chức năng bổ sung. .

import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
3
import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
4
import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
5
import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
6
import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
7
import classtobetested                                                                                                                                                                                      
import unittest                                                                                                                                                                                             

import contextlib                                                                                                                                                                                           

@contextlib.contextmanager                                                                                                                                                                                  
def monkey_patch(module, fn_name, patch):                                                                                                                                                                   
    unpatch = getattr(module, fn_name)                                                                                                                                                                      
    setattr(module, fn_name)                                                                                                                                                                                
    try:                                                                                                                                                                                                    
        yield                                                                                                                                                                                               
    finally:                                                                                                                                                                                                
        setattr(module, fn_name, unpatch)                                                                                                                                                                   


class TestTheClassToBeTested(unittest.TestCase):                                                                                                                                                              
    def test_with_fs_mocks(self):                                                                                                                                                                           
        with monkey_patch(classtobetested.os.path,                                                                                                                                                          
                          'isfile',                                                                                                                                                                         
                          lambda path: path == '/path/to/file'):                                                                                                                                            
            self.assertTrue(classtobetested.testable())                 
8

Làm thế nào để bạn tạo ra một chế giễu trong Python?

Làm thế nào để chúng ta chế giễu trong Python ?...

Viết bài kiểm tra như thể bạn đang sử dụng API bên ngoài thực sự ..

Trong chức năng được kiểm tra, xác định cuộc gọi API nào cần được chế giễu;Đây phải là một con số nhỏ ..

Trong chức năng kiểm tra, vá các cuộc gọi API ..

Thiết lập các phản hồi đối tượng Magicock ..

Chạy bài kiểm tra của bạn ..

Làm cách nào để viết một tệp giả?

Để chế giễu tệp mở và ghi nội dung trên đó, chúng ta có thể sử dụng Mock_open () ....

Gọi phương thức thực tế của chúng tôi FileWriter ().....

khẳng định nếu mocked_file được mở với đường dẫn tệp cụ thể: fake_file_path và viết chế độ mở: w ..

Làm thế nào để chế giễu hoạt động trong Python?

Mock cung cấp một cơ chế mạnh mẽ cho các đối tượng chế giễu, được gọi là patch (), tìm kiếm một đối tượng trong một mô -đun nhất định và thay thế đối tượng đó bằng một giả.Thông thường, bạn sử dụng Patch () làm người trang trí hoặc người quản lý bối cảnh để cung cấp một phạm vi mà bạn sẽ chế giễu đối tượng đích.patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.

Bạn có thể chế giễu một python biến đổi?

Với một biến mô -đun, bạn có thể đặt giá trị trực tiếp hoặc sử dụng giả...