首页 > 解决方案 > 如何使用 python unittest 模拟 aws 库 GlueContext

问题描述

无法从 aws 胶水模拟 GlueContext

我有这些代码行

sc = SparkContext()
gluecontext = GlueContext(sc)
spark = gluecontext.spark_session

如何使用python unittest模拟gluecontext?

如何在 python unittest 中模拟未在本地安装的库?

标签: pythonaws-glue

解决方案


一种方法是将 Glue 库和 Spark 下载到项目的根目录(或根据需要进行配置)

wget https://github.com/awslabs/aws-glue-libs/archive/glue-1.0.zip
wget https://aws-glue-etl-artifacts.s3.amazonaws.com/glue-1.0/spark-2.4.3-bin-hadoop2.8.tgz
unzip glue-1.0.zip -d $PROJECT_ROOT
tar -xf spark-2.4.3-bin-hadoop2.8.tgz -C $PROJECT_ROOT
export SPARK_HOME=$PROJECT_ROOT/spark-2.4.3-bin-spark-2.4.3-bin-hadoop2.8

然后简单地模拟gluecontext

from mock import patch
class Test(unittest.TestCase):
    @patch('awsglue.context.GlueContext')
    @patch('awsglue.utils.getResolvedOptions', side_effect=mock_get_resolved_options)
    def test_method(self, mock_resolve_options, mock_glue_context):
        <your code>

在本地提交测试

$PROJECT_ROOT/aws-glue-libs-glue-1.0/bin/gluepytest $PROJECT_ROOT/tests/

推荐阅读