测试是软件开发中的基础工作,它经常被数据开发者忽视,但是它很重要。在本文中会展示如何使用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. Gin框架源码解析

    Gin框架源码解析 Gin框架是golang的一个常用的web框架,最近一个项目中需要使用到它,所以对这个框架进行了学习.gin包非常短小精悍,不过主要包含的路由,中间件,日志都有了.我们可以追着代码 ...

  2. SVN客户端安装与使用

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6623148.html  一:SVN客户端下载与安装 下载网址:https://tortoisesvn.net/ ...

  3. Python读写文件你真的了解吗?

    内容概述 Python文件操作 针对大文件如何操作 为什么不能修改文件? 你需要知道的基本知识 1. Python文件操作 这一部分内容不是重点,因为很简单网上很多,主要看看文件操作的步骤就可以了. ...

  4. ueditor上传图片尺寸过大导致显示难看的解决办法

    昨天遇到这个问题,我也是折腾成了狗, 到处查,最后收集到三个办法,记录一下. 代码贴这里,方便复制 img { max-width: 100%; /*图片自适应宽度*/ } body { overfl ...

  5. msf登陆Windows 1

    前言:刚做完这个测试,于是,写下自己的测试过程以及测试中遇到的问题解决办法 1. Windows版本适合类型(Win 7 // XP...............) 2. 以XP为靶机,借助工具get ...

  6. #7 找出数组中第k小的数

    「HW面试题」 [题目] 给定一个整数数组,如何快速地求出该数组中第k小的数.假如数组为[4,0,1,0,2,3],那么第三小的元素是1 [题目分析] 这道题涉及整数列表排序问题,直接使用sort方法 ...

  7. 第4章 打包和构建 - Identity Server 4 中文文档(v1.0.0)

    IdentityServer由许多nuget包组成. 4.1 IdentityServer4 nuget | github上 包含核心IdentityServer对象模型,服务和中间件.仅包含对内存配 ...

  8. Odd-e CSD Course Day 2

    首先在第二天中其實談的更多的是在於 Test-Driven 的部分,而第一天談的偏向如何寫出一個好的 A-TDD 案例 但在第二天開始,就不太會照固定的 Topic 進行講述,而且讓團隊成員就像一個真 ...

  9. 使用Common.Logging+log4net规范日志管理【转载】

    使用Common.Logging+log4net规范日志管理   Common.Logging+(log4net/NLog/) common logging是一个通用日志接口,log4net是一个强大 ...

  10. Java开发笔记(六十三)双冒号标记的方法引用

    前面介绍了如何自己定义函数式接口,本文接续函数式接口的实现原理,阐述它在数组处理中的实际应用.数组工具Arrays提供了sort方法用于数组元素排序,可是并未提供更丰富的数组加工操作,比如从某个字符串 ...