测试是软件开发中的基础工作,它经常被数据开发者忽视,但是它很重要。在本文中会展示如何使用Python的uniittest.mock库对一段PySpark代码进行测试。笔者会从数据科学家的视角来进行描述,这意味着本文将不会深入某些软件开发的细节。

本文链接:https://www.cnblogs.com/hhelibeb/p/10508692.html

英文原文:Stop mocking me! Unit tests in PySpark using Python’s mock library

单元测试和mock是什么?

单元测试是一种测试代码片段的方式,确保代码片段按预期工作。Python中的uniittest.mock库,允许人们将部分代码替换为mock对象,并对人们使用这些mock对象的方式进行断言。“mock”的功能如名字所示——它模仿代码中的对象/变量的属性。

最终目标:测试spark.sql(query)

PySpark中最简单的创建dataframe的方式如下:

df = spark.sql("SELECT * FROM table")

虽然它很简单,但依然应该被测试。

准备代码和问题

假设我们为一家电子商务服装公司服务,我们的目标是创建产品相似度表,用某些条件过滤数据,把它们写入到HDFS中。

假设我们有如下的表:

1. Products. Columns: “item_id”, “category_id”.
2. Product_similarity (unfiltered). Columns: “item_id_1”, “item_id_2”, “similarity_score”.

(假设Product_similarity中的相似度分数在0~1之间,越接近1,就越相似。)

查看一对产品和它们的相似度分数是很简单的:

SELECT
s.item_id_1,
s.item_id_2,
s.similarity_score
FROM product_similarity s
WHERE s.item_id_1 != s.item_id_2

where子句将和自身对比的项目移除。否则的话会得到分数为1的结果,没有意义!

要是我们想要创建一个展示相同目录下的产品的相似度的表呢?要是我们不关心鞋子和围巾的相似度,但是想要比较不同的鞋子与鞋子、围巾与围巾呢?这会有点复杂,需要我们连接“product”和“product_similarity”两个表。

查询语句变为:

SELECT
s.item_id_1,
s.item_id_2,
s.similarity_score
FROM product_similarity s
INNER JOIN products p
ON s.item_id_1 = p.item_id
INNER JOIN products q
ON s.item_id_2 = q.item_id
WHERE s.item_id_1 != s.item_id_2
AND p.category_id = q.category_i

我们也可能想得知与每个产品最相似的N个其它项目,在该情况下,查询语句为:

SELECT
s.item_id_1,
s.item_id_2,
s.similarity_score
FROM (
SELECT
s.item_id_1,
s.item_id_2,
s.similarity_score,
ROW_NUMBER() OVER(PARTITION BY item_id_1 ORDER BY similarity_score DESC) as row_num
FROM product_similarity s
INNER JOIN products p
ON s.item_id_1 = p.item_id
INNER JOIN products q
ON s.item_id_2 = q.item_id
WHERE s.item_id_1 != s.item_id_2
AND p.category_id = q.category_id
)
WHERE row_num <= 10

(假设N=10)

现在,要是我们希望跨产品目录比较和在产品目录内比较两种功能成为一个可选项呢?我们可以通过使用名为same_category的布尔变量,它会控制一个字符串变量same_category_q的值,并将其传入查询语句(通过.format())。如果same_category为True,则same_category_q中为inner join的内容,反之,则为空。查询语句如下:

'''
SELECT
s.item_id_1,
s.item_id_2,
s.similarity_score
FROM product_similarity s
{same_category_q}
'''.format(same_category_q='') # Depends on value of same_category boolean

(译注:Python 3.6以上可以使用f-Strings代替format)

让我们把它写得更清楚点,用function包装一下,

def make_query(same_category, table_paths): 

    if same_category is True:
same_category_q = '''
INNER JOIN {product_table} p
ON s.item_id_1 = p.item_id
INNER JOIN {product_table} q
ON s.item_id_2 = q.item_id
WHERE item_id_1 != item_id_2
AND p.category_id = q.category_id
'''.format(product_table=table_paths["products"]["table"])
else:
same_category_q = '' return same_category_q

到目前为止,很不错。我们输出了same_category_q,因此可以通过测试来确保它确实返回了所需的值。

回忆我们的目标,我们需要将dataframe写入HDFS,我们可以通过如下方法来测试函数:

def create_new_table(spark, table_paths, params, same_category_q):

    similarity_table = table_paths["product_similarity"]["table"]

    created_table = spark.sql(create_table_query.format(similarity_table=similarity_table,
same_category_q=same_category_q,
num_items=params["num_items"])) # Write table to some path
created_table.coalesce(1).write.save(table_paths["created_table"]["path"],
format="orc", mode="Overwrite")

添加查询的第一部分和一个主方法,完成我们的脚本,得到:

import pyspark
from pyspark.sql import SparkSession create_table_query = '''
SELECT
item_id_1,
item_id_2
FROM (
SELECT
item_id_1,
item_id_2,
ROW_NUMBER() OVER(PARTITION BY item_id_1 ORDER BY similarity_score DESC) as row_num
FROM {similarity_table} s
{same_category_q}
)
WHERE row_num <= {num_items}
''' def create_new_table(spark, table_paths, params, from_date, to_date, same_category_q): similarity_table = table_paths["product_similarity"]["table"] created_table = spark.sql(create_table_query.format(similarity_table=similarity_table,
same_category_q=same_category_q,
num_items=params["num_items"])) # Write table to some path
created_table.coalesce(1).write.save(table_paths["created_table"]["path"],
format="orc", mode="Overwrite") def make_query(same_category, table_paths): if same_category is True:
same_category_q = '''
INNER JOIN {product_table} p
ON s.item_id_1 = p.item_id
INNER JOIN {product_table} q
ON s.item_id_2 = q.item_id
WHERE item_id_1 != item_id_2
AND p.category_id = q.category_id
'''.format(product_table=table_paths["product_table"]["table"])
else:
same_category_q = '' return same_category_q if __name__ == "__main__": spark = (SparkSession
.builder
.appName("testing_tutorial")
.enableHiveSupport()
.getOrCreate()) same_category = True # or False
table_paths = foo # Assume paths are in some JSON
params = bar same_category_q, target_join_q = make_query(same_category, table_paths)
create_new_table(spark, table_paths, params, same_category_q)

这里的想法是,我们需要创建为脚本中的每个函数创建function,名字一般是test_name_of_function()。需要通过断言来验证function的行为是否符合预期。

测试查询-make_query

首先,测试make_query。make_query有两个输入参数:一个布尔变量和某些表路径。它会基于布尔变量same_category返回不同的same_category_q。我们做的事情有点像是一个if-then语句集:

1. If same_category is True, then same_category_q = “INNER JOIN …”
2. If same_category is False, then same_category_q = “” (empty)

我们要做的是模拟make_query的参数,把它们传递给function,接下来测试是否得到期望的输出。因为test_paths是个目录,我们无需模拟它。测试脚本如下,说明见注释:

def test_make_query_true(mocker):

    # Create some fake table paths
test_paths = {
"product_table": {
"table": "products",
},
"similarity_table": {
"table": "product_similarity"
}
} # Call the function with our paths and "True"
same_category_q = make_query(True, test_paths)
# We want same_category_q to be non-empty
assert same_category_q != '' def test_make_query_false(mocker): # As above, create some fake paths
test_paths = {
"product_table": {
"table": "products",
},
"similarity_table": {
"table": "product_similarity"
}
} same_category_q = make_query(False, test_paths)
# This time, we want same_category_q to be empty
assert same_category_q == ''

就是这么简单!

测试表创建

下一步,我们需要测试create_new_table的行为。逐步观察function,我们可以看到它做了几件事,有几个地方可以进行断言和模拟。注意,无论何时,只要程序中有某些类似df.write.save.something.anotherthing的内容,我们就需要模拟每个操作和它们的输出。

  1. 这个function使用spark作为参数,这需要被模拟。
  2. 通过调用spark.sql(create_table_query.format(**some_args))来创建created_table。我们需要断言spark.sql()只被调用了一次。我们也需要模拟spark.sql()的输出。
  3. Coalesce created_table。保证调用coalesce()时的参数是1。模拟输出。
  4. 写coalesced table,我们需要模拟.write,模拟调用它的输出。
  5. 将coalesced table保存到一个路径。确保它的调用伴随着正确的参数。

和前面一样,测试脚本如下:

ef test_create_new_table(mocker):

    # Mock all our variables
mock_spark = mock.Mock()
mock_category_q = mock.Mock()
mock_created_table = mock.Mock()
mock_created_table_coalesced = mock.Mock()
# Calling spark.sql with create_table_query returns created_table - we need to mock it
mock_spark.sql.side_effect = [mock_created_table]
# Mock the output of calling .coalesce on created_table
mock_created_table.coalesce.return_value = mock_created_table_coalesced
# Mock the .write as well
mock_write = mock.Mock()
# Mock the output of calling .write on the coalesced created table
mock_created_table_coalesced.write = mock_write test_paths = {
"product_table": {
"table": "products",
},
"similarity_table": {
"table": "product_similarity"
},
"created_table": {
"path": "path_to_table",
}
}
test_params = {
"num_items": 10,
} # Call our function with our mocks
create_new_table(mock_spark, test_paths, test_params, mock_category_q)
# We only want spark.sql to have been called once, so assert that
assert 1 == mock_spark.sql.call_count
# Assert that we did in fact call created_table.coalesce(1)
mock_created_table.coalesce.assert_called_with(1)
# Assert that the table save path was passed in properly
mock_write.save.assert_called_with(test_paths["created_table"]["path"],
format="orc", mode="Overwrite")

最后,把每样东西保存在一个文件夹中,如果你想的话,你需要从相应的模块中导入function,或者把所有东西放在同一个脚本中。

为了测试它,在命令行导航到你的文件夹(cd xxx),然后执行:

python -m pytest final_test.py.

你可以看到类似下面的输出,

serena@Comp-205:~/workspace$ python -m pytest testing_tutorial.py
============================= test session starts ==============================
platform linux -- Python 3.6.4, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
rootdir: /home/serena/workspace/Personal,
inifile: plugins: mock-1.10.0 collected 3 items testing_tutorial.py ...
[100%]
=========================== 3 passed in 0.01 seconds ===========================

结语

以上是全部内容。希望你觉得有所帮助。当我试图弄明白如何mock的时候,我希望可以遇到类似这样一篇文章。

现在就去做吧,就像Stewie所说的那样,(don’t) stop mocking me (functions)!

使用Python的Mock库进行PySpark单元测试的更多相关文章

  1. 利用Python中的mock库对Python代码进行模拟测试

    这篇文章主要介绍了利用Python中的mock库对Python代码进行模拟测试,mock库自从Python3.3依赖成为了Python的内置库,本文也等于介绍了该库的用法,需要的朋友可以参考下     ...

  2. 【转】利用Python中的mock库对Python代码进行模拟测试

    出处 https://www.toptal.com/python/an-introduction-to-mocking-in-python http://www.oschina.net/transla ...

  3. Python 的mock模拟测试介绍

    如何不靠耐心测试 可能我们正在写一个社交软件并且想测试一下"发布到Facebook的功能",但是我们不希望每次运行测试集的时候都发布到Facebook上. Python的unitt ...

  4. python第三方库系列之十九--python測试使用的mock库

    一.为什么须要mock         在写unittest的时候,假设系统中有非常多外部依赖,我们不须要也不希望把全部的部件都执行一遍.比方,要验证分享到微博的功能,假设每次測试的时候都要真实地把接 ...

  5. python 各种开源库

    测试开发 来源:https://www.jianshu.com/p/ea6f7fb69501 Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. 链接 sel ...

  6. Python常用的库简单介绍一下

    Python常用的库简单介绍一下fuzzywuzzy ,字符串模糊匹配. esmre ,正则表达式的加速器. colorama 主要用来给文本添加各种颜色,并且非常简单易用. Prettytable ...

  7. Python的常用库

    读者您好.今天我将介绍20个属于我常用工具的Python库,我相信你看完之后也会觉得离不开它们.他们是: Requests.Kenneth Reitz写的最富盛名的http库.每个Python程序员都 ...

  8. Python之Mock的入门

    参考文章: https://segmentfault.com/a/1190000002965620 一.Mock是什么 Mock这个词在英语中有模拟的这个意思,因此我们可以猜测出这个库的主要功能是模拟 ...

  9. python 三方面库整理

    测试开发 Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. selenium - web UI自动化测试. –推荐 mechanize- Python中有状 ...

随机推荐

  1. Linq使用Group By

    1.简单形式: var q = from p in db.Products group p by p.CategoryID into g select g; 语句描述:Linq使用Group By按C ...

  2. JS 中 原生方法 (二) --- 数组 (修---添加ES6新增)

    const arr = [1, 2, 3, 5, 'a', 'b'] /** * * length * 这个只能被 称之为 数组的原生属性, 返回 一个 number * arr.length */ ...

  3. 从锅炉工到AI专家(10)

    RNN循环神经网络(Recurrent Neural Network) 如同word2vec中提到的,很多数据的原型,前后之间是存在关联性的.关联性的打破必然造成关键指征的丢失,从而在后续的训练和预测 ...

  4. UPC:ABS

    问题 G: ABS 时间限制: 1 Sec  内存限制: 128 MB提交: 537  解决: 186[提交] [状态] [讨论版] [命题人:admin] 题目描述 We have a deck c ...

  5. Eclipse查看JDK源码(非常详细)

    Eclipse查看源码的方式其实很简单,打开项目,然后按着ctrl,然后把鼠标光标移动到你想查看的方法或者对象上,这时会出现一条下划线,然后点击鼠标左键就可以进入那个方法或者对象了.但是有的情况下会出 ...

  6. java web 项目打包(war 包)并部署

    1.在eclipse中右键单击项目,然后Export选择WAR file,生成项目的WAR文件.具体步骤请看图片详细操作步骤: 2.把生成的WAR文件放到tomcat解压之后的webapps文件夹下. ...

  7. Perl IO:IO重定向

    文件句柄和文件描述符的关系 文件描述符是操作系统的资源,对于实体文件来说,每打开一次文件,操作系统都会为该进程分配一个文件描述符来关联(指向)这个文件,以后操作文件数据都根据这个文件描述符来操作,而不 ...

  8. Spring Cloud Alibaba与Spring Boot、Spring Cloud之间不得不说的版本关系

    这篇博文是临时增加出来的内容,主要是由于最近连载<Spring Cloud Alibaba基础教程>系列的时候,碰到读者咨询的大量问题中存在一个比较普遍的问题:版本的选择.其实这类问题,在 ...

  9. JavaScript小实例:拖拽应用(二)

    经常在网站别人的网站的注册页中看到一个拖拽验证的效果,就是它的验证码刚开始不出来,而是有一个拖拽的条,你必须将这个拖拽条拖到底,验证码才出来,说了感觉跟没说一样,你还是不理解,好吧,我给个图你看看: ...

  10. C# /VB.NET操作Word批注(一)—— 插入、修改、删除Word批注

    批注内容可以是对某段文字或内容的注释,也可以是对文段中心思想的概括提要,或者是对文章内容的评判.疑问,以及在阅读时给自己或他人起到提示作用.本篇文章中将介绍如何在C#中操作Word批注,主要包含以下要 ...