简体   繁体   English

如何在单元测试时正确测试 pcollection 长度 Apache Beam

[英]How to properly test pcollection length when unit testing Apache Beam

I am wondering which is the best way to test check the lenght of the output produced by a beam pipeline.我想知道哪个是测试检查束流水线产生的 output 长度的最佳方法。

I have some testcode like this:我有一些这样的测试代码:

test_data = [
    {'kind': 'storage#object', 'name': 'file1.doc', 'contentType': 'application/octet-stream', 'bucket': 'bucket123' },
    {'kind': 'storage#object', 'name': 'file2.pdf', 'contentType': 'application/pdf','bucket': 'bucket234'},
    {'kind': 'storage#object', 'name': 'file3.msg', 'contentType': 'message/rfc822', 'bucket': 'bucket345'}
]

with TestPipeline() as p:
   output = (p 
             | beam.Create(test_data)
             | beam.ParDo(DoFn_To_Test()).with_outputs('ok','error')
   )

I want to test sure that all elements in the test_data list go to 'output.ok'.我想测试确保 test_data 列表中的所有元素 go 到“output.ok”。 I think way to do it is to count them like this:我认为这样做的方法是像这样计算它们:

with TestPipeline() as p:
   output = (p 
             | beam.Create(testdata) 
             | beam.ParDo(DoFn_To_Test()).with_outputs('ok','error')
   )

   okay_count = (output.ok | beam.Map(lambda x: ('dummy_key',x)) 
                 | beam.GroupByKey()  # This gets ('dumm_key',[element1,element2....])
                 | beam.Map(lambda x: len(x[1]) )  # Drop the key and get the lengh of the list
   )

   # And finally check^H^H^H^H^H^H assert the count is correct:
   assert_that(okay_count, equal_to([len(test_data)])

This works;这行得通; but I don't feel this is the best way to do it, and I am sure there are more ways to do it.但我认为这不是最好的方法,而且我相信还有更多方法可以做到。

Best option (by now)最佳选择(目前)

This is the best option suggested up to date: using beam.combiners.Count.Globally()这是迄今为止建议的最佳选择:使用 beam.combiners.Count.Globally()

with TestPipeline() as p:
   output = (p 
             | beam.Create(testdata) 
             | beam.ParDo(DoFn_To_Test()).with_outputs('ok','error')
   )

   okay_count = output | beam.combiners.Count.Globally()
   assert_that(okay_count, equal_to([len(test_data)])

You answered your own question in the the question.你在问题中回答了你自己的问题。 Writing it here as an answer:写在这里作为答案:

with TestPipeline() as p:
   output = (p 
             | beam.Create(testdata) 
             | beam.ParDo(DoFn_To_Test()).with_outputs('ok','error')
   )

   okay_count = output | beam.combiners.Count.Globally()
   assert_that(okay_count, equal_to([len(test_data)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM