Python单元测试报错:搜索文件时需bytes-like对象而非str
解决文件搜索时的TypeError: bytes-like object is required问题
问题原因
你用rb模式打开文件后,生成的mmap对象是字节流类型,但传入的搜索参数是字符串,mmap.find()方法要求传入字节对象,因此抛出类型错误。另外原代码中finally块里的f.close()是多余的——with上下文管理器会自动关闭文件,手动调用会触发额外错误。
解决办法
方法1:将搜索字符串转为字节类型
修改被测试的search方法,把字符串参数编码为字节后再调用find:
def search(self, file: str, search: str) -> bool: """ Search for a string in a file. """ print('-------') print(file) print(search) r = False # 初始化默认返回值,避免异常后无返回 try: search_bytes = search.encode('utf-8') with open(file, 'rb', 0) as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as s: r = s.find(search_bytes) != -1 except FileNotFoundError: self.Error().file_not_found_error(file) except OSError: self.Error().os_error(file) except Exception as err: self.Error().exception(file, err) return r
方法2:使用文本模式打开文件
如果仅处理文本文件,直接用文本模式打开文件和mmap,这样可以直接使用字符串搜索:
def search(self, file: str, search: str) -> bool: """ Search for a string in a file. """ print('-------') print(file) print(search) r = False try: with open(file, 'r', encoding='utf-8') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ, encoding='utf-8') as s: r = s.find(search) != -1 except FileNotFoundError: self.Error().file_not_found_error(file) except OSError: self.Error().os_error(file) except Exception as err: self.Error().exception(file, err) return r
额外说明
测试代码无需修改——你已经用文本模式写入了测试文件,两种解决方法都能兼容现有测试逻辑。
内容的提问来源于stack exchange,提问作者jnbdz
相关产品推荐
相关产品推荐

