Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pytest Mock socket.socket.connect函数_Python_Sockets_Mocking_Pytest - Fatal编程技术网

Python Pytest Mock socket.socket.connect函数

Python Pytest Mock socket.socket.connect函数,python,sockets,mocking,pytest,Python,Sockets,Mocking,Pytest,我从配置文件中读取IP,并验证是否可以通过socket.socket.connect访问特定端口 我想做一个测试,读取一个包含信息的文件(自动验证IP)并进行验证 为了能够让测试通过,需要模拟IP,这样函数“check_connection”将返回True 我不想让它依赖于真正的设备 这是怎么做到的 在Stackoverflow上可以找到一些信息(),但不知道如何与包含IP信息的文件相关地实现它,该信息将在从类调用的函数中进行检查 代码片段: 验证_file.py def check_conne

我从配置文件中读取IP,并验证是否可以通过socket.socket.connect访问特定端口

我想做一个测试,读取一个包含信息的文件(自动验证IP)并进行验证

为了能够让测试通过,需要模拟IP,这样函数“check_connection”将返回True

我不想让它依赖于真正的设备

这是怎么做到的

在Stackoverflow上可以找到一些信息(),但不知道如何与包含IP信息的文件相关地实现它,该信息将在从类调用的函数中进行检查

代码片段:

验证_file.py

def check_connection(connection_ip: str, connection_port: int) -> bool:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((connection_ip, connection_port))
        s.shutdown(2)
        s.close()
        return True
    except Exception as e:
        print(f"Unable to connect to IP {connection_ip}.\n {e}")
        return False


class validateconfiguration:
   def __init__(self, path_config):
     self.config = configparser.ConfigParser()
     self.config.read_file(open(path_config))
     self.information = dict(self.config["information "])

   …..
   def read_serverip(self):
       ip=self.information['ip']
       if check_connection(ip, 90):
            print("server exist")
        else:
            return False
test.py

import pytest
from validate_file import validateconfguration

def test_validate_file(tmpdir):
    configfile = configparser.ConfigParser()
    configfile['information'] = {'ip’: '0.0.0.0'}

    filename_configfile= tmpdir.join("config.ini")
    with open(filename_configfile, 'w') as file:
        correct_full_config.write(file)

    foobar = validateconfiguration(filename_configfile)
    assert foobar.read_serverip()== True
我想测试的两件事:

  • 可以进行连接(提供正确的IP)
  • 无法进行连接(提供的IP错误)