[英]Python read_text() adding extra strings
I've created a function that takes in a file with dynamic SQL (and parameters) then returns the end SQL result.我创建了一个函数,该函数接收带有动态 SQL(和参数)的文件,然后返回最终的 SQL 结果。 It seems to be adding extra strings because my unit test is failing and it shows extra strings.它似乎添加了额外的字符串,因为我的单元测试失败并且它显示了额外的字符串。
My function:我的功能:
def file_to_sql(filename, kwargs=None):
"""Read file and return SQL statement.
Parameters
----------
filename: str
Name of the file to read.
kwargs : dict
Keyword arguments to be passed into your SQL statement.
"""
python_dir = Path('logic/extract/python3')
python_file_path = python_dir / '{}'.format(filename)
sql = python_file_path.read_text().format(**kwargs)
return sql
My unit test:我的单元测试:
def test_python_file_with_kwargs_to_sql():
sql = file_to_sql(filename="select_all_from_{table}.py", kwargs={
'table': 'sandbox.test_table'
})
assert sql == "SELECT * FROM sandbox.test_table;"
select_all_from_{table}.py: select_all_from_{table}.py:
"SELECT * FROM {table};"
Unit test failure message:单元测试失败消息:
================================== FAILURES ===================================
_____________________ test_python_file_with_kwargs_to_sql _____________________
def test_python_file_with_kwargs_to_sql():
sql = file_to_sql(filename="select_all_from_{table}.py", kwargs={
'table': 'sandbox.test_table'
})
> assert sql == "SELECT * FROM sandbox.test_table;"
E assert '"SELECT * FR....test_table;"' == 'select * from...x.test_table;'
E - "SELECT * FROM sandbox.test_table;"
E + SELECT * FROM sandbox.test_table;
tests\unit_tests\transform\test_preprocess.py:19: AssertionError
================ 1 failed, 2 passed, 4 skipped in 1.40 seconds ================
There are two reasons your unit test is failing:您的单元测试失败有两个原因:
Your sql
string is in mixed cases ("SELECT" and "FROM" are upper cases) whereas your comparison string is in all lower cases.您的sql
字符串是大小写混合的(“SELECT”和“FROM”是大写),而您的比较字符串是全部小写。
The text within select_all_from_{table}.py
are in double quotes but your comparison string doesn't have the double quotes. select_all_from_{table}.py
中的文本是双引号,但您的比较字符串没有双引号。
Since read_text()
reads the file content as str
you don't need the double quotes.由于read_text()
将文件内容读取为str
您不需要双引号。 Remove the double quotes from your file and for good practice, do a case insensitive test:从您的文件中删除双引号,为了好的做法,请进行不区分大小写的测试:
sql.lower() == 'select * from sandbox.test_table'.lower()
Or just sql.lower() == 'select * from sandbox.test_table'
will suffice in this particular case.或者只是sql.lower() == 'select * from sandbox.test_table'
在这种特殊情况下就足够了。
For unit tests it is best you be vigilant about your input and output and make sure your tests are exact.对于单元测试,最好对输入和输出保持警惕,并确保测试准确无误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.