You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by GitBox <gi...@apache.org> on 2022/08/15 17:38:48 UTC

[GitHub] [beam] pabloem opened a new pull request, #22233: Trying out property-based tests for Beam python coders

pabloem opened a new pull request, #22233:
URL: https://github.com/apache/beam/pull/22233

   I discovered this little library and decided to try it out to write a couple tests.
   
   We may be able to use it to write some simple x-lang coder tests? : )
   
   For info (and examples) of the library: https://hypothesis.readthedocs.io/en/latest/quickstart.html
   
   fyi: @TheNeuralBit @robertwb 
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] [**Choose reviewer(s)**](https://beam.apache.org/contribute/#make-your-change) and mention them in a comment (`R: @username`).
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://beam.apache.org/contribute/#make-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/workflows/Build%20python%20source%20distribution%20and%20wheels/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/workflows/Python%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/workflows/Java%20Tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1245940612

   Run Python PreCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] Abacn commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
Abacn commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961646234


##########
sdks/python/apache_beam/coders/row_coder.py:
##########
@@ -150,7 +150,9 @@ def _coder_from_type(field_type):
 def _nonnull_coder_from_type(field_type):
   type_info = field_type.WhichOneof("type_info")
   if type_info == "atomic_type":
-    if field_type.atomic_type in (schema_pb2.INT32, schema_pb2.INT64):
+    if field_type.atomic_type in (schema_pb2.INT16,

Review Comment:
   From #19815 INT16 was encoded in BigEndianShortCoder in Java side but just not implemented in other SDKs. This may cause data corruption. The "Encountered a type that is not currently supported by RowCoder" Exception is currently correctly raised.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1245754917

   Run Python 3.8 PostCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] TheNeuralBit commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
TheNeuralBit commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r964804914


##########
sdks/python/apache_beam/coders/row_coder.py:
##########
@@ -162,6 +164,8 @@ def _nonnull_coder_from_type(field_type):
       return BooleanCoder()
     elif field_type.atomic_type == schema_pb2.BYTES:
       return BytesCoder()
+    elif field_type.atomic_type == schema_pb2.BYTE:

Review Comment:
   Thanks for raising this @Abacn :)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1245754699

   Run Python PreCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] Abacn commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
Abacn commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961647096


##########
sdks/python/apache_beam/coders/row_coder.py:
##########
@@ -162,6 +164,8 @@ def _nonnull_coder_from_type(field_type):
       return BooleanCoder()
     elif field_type.atomic_type == schema_pb2.BYTES:
       return BytesCoder()
+    elif field_type.atomic_type == schema_pb2.BYTE:

Review Comment:
   Same here (according to #19815)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961859503


##########
sdks/python/apache_beam/coders/row_coder.py:
##########
@@ -162,6 +164,8 @@ def _nonnull_coder_from_type(field_type):
       return BooleanCoder()
     elif field_type.atomic_type == schema_pb2.BYTES:
       return BytesCoder()
+    elif field_type.atomic_type == schema_pb2.BYTE:

Review Comment:
   removed. Thanks!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1238342025

   Run Python 3.8 PostCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] TheNeuralBit commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
TheNeuralBit commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1188215850

   Neat! This could be helpful for DataFrame tests too. frames_test.py is loaded with tests that just make sure Beam gets the same result as pandas for a certain operation. These all just have some arbitrary test data, it could catch some issues if we generate the data with hypothesis instead.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1235801022

   @Abacn ptal? : )


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1245772181

   Run Python PreCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961312211


##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]
+
+SCHEMA_TYPES_TO_STRATEGY = {
+    str: st.text(),
+    bytes: st.binary(),
+    # Maximum datetime on year 3000 to conform to Windows OS limits.
+    Timestamp: st.datetimes(
+        min_value=datetime(1970, 1, 1, 1, 1),
+        max_value=datetime(
+            3000, 1, 1, 0,
+            0)).map(lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
+    int: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
+    np.int64: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
+    np.uint64: st.integers(min_value=0, max_value=1 << 64 - 1),
+    bool: st.booleans()
+}
+
+# A hypothesis strategy that generates schemas.
+# A schema is a list containing tuples of strings (field names), types (field
+# types) and boolean (nullable or not).
+# This strategy currently generates rows with simple types (i.e. non-list, and
+# non-map fields).
+SCHEMA_GENERATOR_STRATEGY = st.lists(
+    st.tuples(
+        st.text(ascii_letters + digits + '_', min_size=1),
+        st.sampled_from(SCHEMA_TYPES),
+        st.booleans()))
+
+
+class ProperyTestingCoders(unittest.TestCase):
+  @given(st.text())
+  def test_string_coder(self, txt: str):
+    coder = StrUtf8Coder()
+    self.assertEqual(coder.decode(coder.encode(txt)), txt)
+
+  @given(st.floats())
+  def test_float_coder(self, num: float):
+    coder = FloatCoder()
+    test_num = coder.decode(coder.encode(num))
+    if math.isnan(num):
+      # This special branch is needed because by definition
+      # nan != nan.
+      self.assertTrue(math.isnan(test_num))
+    else:
+      self.assertEqual(coder.decode(coder.encode(num)), num)
+
+  @settings(deadline=None, print_blob=True)
+  @given(st.data())
+  def test_row_coder(self, data: st.DataObject):
+    """Generate rows and schemas, and test their encoding/decoding.
+
+    The schemas are generated based on the SCHEMA_GENERATOR_STRATEGY.
+    """
+    schema = data.draw(SCHEMA_GENERATOR_STRATEGY)
+    # Assume that the cardinality of the set of names is the same
+    # as the length of the schema. This means there's no duplicate
+    # names for fields.
+    # If this condition does not hold, then we must not continue the
+    # test.
+    assume(len({name for name, _, _ in schema}) == len(schema))
+    assume(
+        len({n[0]
+             for n, _, _ in schema}.intersection(set(digits + '_'))) == 0)
+    RowType = typing.NamedTuple(  # type: ignore
+        'RandomRowType',
+        [(name, type_ if not nullable else typing.Optional[type_]) for name,
+         type_,
+         nullable in schema])

Review Comment:
   added to the above issue.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1235099212

   Run Python 3.8 PostCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1246019173

   thanks y'all


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1238341819

   I've removed changes to RowCoder. I'll merge after tests pass now. Thanks y'all.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] github-actions[bot] commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1181517205

   Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment `assign set of reviewers`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem closed pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem closed pull request #22233: Trying out property-based tests for Beam python coders
URL: https://github.com/apache/beam/pull/22233


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] codecov[bot] commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
codecov[bot] commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1215618540

   # [Codecov](https://codecov.io/gh/apache/beam/pull/22233?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#22233](https://codecov.io/gh/apache/beam/pull/22233?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (160abca) into [master](https://codecov.io/gh/apache/beam/commit/a8775f0a4ac13fea440dc6e4b18f1bd5f821fcaf?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (a8775f0) will **decrease** coverage by `0.00%`.
   > The diff coverage is `n/a`.
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #22233      +/-   ##
   ==========================================
   - Coverage   74.25%   74.24%   -0.01%     
   ==========================================
     Files         702      705       +3     
     Lines       92961    93267     +306     
   ==========================================
   + Hits        69028    69250     +222     
   - Misses      22666    22750      +84     
     Partials     1267     1267              
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | python | `83.58% <ø> (-0.06%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://codecov.io/gh/apache/beam/pull/22233?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [.../python/apache\_beam/testing/test\_stream\_service.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vdGVzdGluZy90ZXN0X3N0cmVhbV9zZXJ2aWNlLnB5) | `88.09% <0.00%> (-4.77%)` | :arrow_down: |
   | [sdks/python/apache\_beam/utils/interactive\_utils.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vdXRpbHMvaW50ZXJhY3RpdmVfdXRpbHMucHk=) | `95.12% <0.00%> (-2.44%)` | :arrow_down: |
   | [sdks/python/apache\_beam/utils/subprocess\_server.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vdXRpbHMvc3VicHJvY2Vzc19zZXJ2ZXIucHk=) | `56.54% <0.00%> (-2.20%)` | :arrow_down: |
   | [sdks/python/apache\_beam/internal/dill\_pickler.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vaW50ZXJuYWwvZGlsbF9waWNrbGVyLnB5) | `85.61% <0.00%> (-1.44%)` | :arrow_down: |
   | [sdks/python/apache\_beam/io/source\_test\_utils.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vaW8vc291cmNlX3Rlc3RfdXRpbHMucHk=) | `88.01% <0.00%> (-1.39%)` | :arrow_down: |
   | [...che\_beam/runners/interactive/interactive\_runner.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vcnVubmVycy9pbnRlcmFjdGl2ZS9pbnRlcmFjdGl2ZV9ydW5uZXIucHk=) | `90.06% <0.00%> (-1.33%)` | :arrow_down: |
   | [...hon/apache\_beam/runners/direct/test\_stream\_impl.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vcnVubmVycy9kaXJlY3QvdGVzdF9zdHJlYW1faW1wbC5weQ==) | `93.28% <0.00%> (-0.75%)` | :arrow_down: |
   | [sdks/python/apache\_beam/runners/direct/executor.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vcnVubmVycy9kaXJlY3QvZXhlY3V0b3IucHk=) | `96.46% <0.00%> (-0.55%)` | :arrow_down: |
   | [...dks/python/apache\_beam/options/pipeline\_options.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vb3B0aW9ucy9waXBlbGluZV9vcHRpb25zLnB5) | `94.34% <0.00%> (-0.42%)` | :arrow_down: |
   | [sdks/python/apache\_beam/transforms/combiners.py](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vdHJhbnNmb3Jtcy9jb21iaW5lcnMucHk=) | `93.05% <0.00%> (-0.39%)` | :arrow_down: |
   | ... and [53 more](https://codecov.io/gh/apache/beam/pull/22233/diff?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | |
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] Abacn commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
Abacn commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961935382


##########
sdks/python/apache_beam/coders/row_coder.py:
##########
@@ -162,6 +164,8 @@ def _nonnull_coder_from_type(field_type):
       return BooleanCoder()
     elif field_type.atomic_type == schema_pb2.BYTES:
       return BytesCoder()
+    elif field_type.atomic_type == schema_pb2.BYTE:

Review Comment:
   @pabloem commented here



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1235098917

   note @TheNeuralBit that I added a few things to RowCoder


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1182555838

   Example of the sort of failures that these tests will find:
   ```
   dt = datetime.datetime(3002, 1, 1, 0, 0)
   >           lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
           int: st.integers(min_value=-(1 << 64 - 1), max_value=1 << 64 - 1),
           np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
           np.int64: st.integers(min_value=-(1 << 64 - 1), max_value=1 << 64 - 1),
           np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
           np.uint64: st.integers(min_value=0, max_value=1 << 65 - 1),
           bool: st.booleans()
       }
   E   OSError: [Errno 22] Invalid argument
   ```
   
   In this case, datetime in year 3002 is not supported? Taking a look...


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] Abacn commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
Abacn commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961916145


##########
sdks/python/apache_beam/coders/row_coder.py:
##########
@@ -162,6 +164,8 @@ def _nonnull_coder_from_type(field_type):
       return BooleanCoder()
     elif field_type.atomic_type == schema_pb2.BYTES:
       return BytesCoder()
+    elif field_type.atomic_type == schema_pb2.BYTE:

Review Comment:
   It seems OK because when BytesCoder encoding/decoding single byte with nested=False is the same as Java's ByteCoder (write one bytes); but if the stream has other data after this byte it is not the case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961914182


##########
sdks/python/apache_beam/coders/row_coder.py:
##########
@@ -162,6 +164,8 @@ def _nonnull_coder_from_type(field_type):
       return BooleanCoder()
     elif field_type.atomic_type == schema_pb2.BYTES:
       return BytesCoder()
+    elif field_type.atomic_type == schema_pb2.BYTE:

Review Comment:
   - nvm - Byte seems to be okay. Should I leave it as is?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1235787007

   Run Python 3.8 PostCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1216889715

   r: @TheNeuralBit 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem merged pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem merged PR #22233:
URL: https://github.com/apache/beam/pull/22233


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] github-actions[bot] commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1216977203

   Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on PR #22233:
URL: https://github.com/apache/beam/pull/22233#issuecomment-1217238580

   Run Python_PVR_Flink PreCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] TheNeuralBit commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
TheNeuralBit commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r959943053


##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]
+
+SCHEMA_TYPES_TO_STRATEGY = {
+    str: st.text(),
+    bytes: st.binary(),
+    # Maximum datetime on year 3000 to conform to Windows OS limits.
+    Timestamp: st.datetimes(
+        min_value=datetime(1970, 1, 1, 1, 1),
+        max_value=datetime(
+            3000, 1, 1, 0,
+            0)).map(lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
+    int: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
+    np.int64: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
+    np.uint64: st.integers(min_value=0, max_value=1 << 64 - 1),

Review Comment:
   Is it intentional to have unsigned ints here? They're not supported in Beam schemas.



##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]

Review Comment:
   It would be nice to have a way to keep this up to date as new types are added in schemas.py. Perhaps a test that checks this set is equivalent to the keys in PRIMITIVE_TO_ATOMIC_TYPE: https://github.com/apache/beam/blob/149ed074428ff9b5344169da7d54e8ee271aaba1/sdks/python/apache_beam/typehints/schemas.py#L104
   
   Plus the registered logical types: https://github.com/apache/beam/blob/149ed074428ff9b5344169da7d54e8ee271aaba1/sdks/python/apache_beam/typehints/schemas.py#L505



##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]
+
+SCHEMA_TYPES_TO_STRATEGY = {
+    str: st.text(),
+    bytes: st.binary(),
+    # Maximum datetime on year 3000 to conform to Windows OS limits.
+    Timestamp: st.datetimes(
+        min_value=datetime(1970, 1, 1, 1, 1),
+        max_value=datetime(
+            3000, 1, 1, 0,
+            0)).map(lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
+    int: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
+    np.int64: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
+    np.uint64: st.integers(min_value=0, max_value=1 << 64 - 1),
+    bool: st.booleans()
+}
+
+# A hypothesis strategy that generates schemas.
+# A schema is a list containing tuples of strings (field names), types (field
+# types) and boolean (nullable or not).
+# This strategy currently generates rows with simple types (i.e. non-list, and
+# non-map fields).
+SCHEMA_GENERATOR_STRATEGY = st.lists(
+    st.tuples(
+        st.text(ascii_letters + digits + '_', min_size=1),
+        st.sampled_from(SCHEMA_TYPES),
+        st.booleans()))
+
+
+class ProperyTestingCoders(unittest.TestCase):
+  @given(st.text())
+  def test_string_coder(self, txt: str):
+    coder = StrUtf8Coder()
+    self.assertEqual(coder.decode(coder.encode(txt)), txt)
+
+  @given(st.floats())
+  def test_float_coder(self, num: float):
+    coder = FloatCoder()
+    test_num = coder.decode(coder.encode(num))
+    if math.isnan(num):
+      # This special branch is needed because by definition
+      # nan != nan.
+      self.assertTrue(math.isnan(test_num))
+    else:
+      self.assertEqual(coder.decode(coder.encode(num)), num)
+
+  @settings(deadline=None, print_blob=True)
+  @given(st.data())
+  def test_row_coder(self, data: st.DataObject):
+    """Generate rows and schemas, and test their encoding/decoding.
+
+    The schemas are generated based on the SCHEMA_GENERATOR_STRATEGY.
+    """
+    schema = data.draw(SCHEMA_GENERATOR_STRATEGY)
+    # Assume that the cardinality of the set of names is the same
+    # as the length of the schema. This means there's no duplicate
+    # names for fields.
+    # If this condition does not hold, then we must not continue the
+    # test.
+    assume(len({name for name, _, _ in schema}) == len(schema))
+    assume(
+        len({n[0]
+             for n, _, _ in schema}.intersection(set(digits + '_'))) == 0)
+    RowType = typing.NamedTuple(  # type: ignore
+        'RandomRowType',
+        [(name, type_ if not nullable else typing.Optional[type_]) for name,
+         type_,
+         nullable in schema])

Review Comment:
   Another potential follow-up: Add a test that's parameterized by the schema proto instead of a generated row type. There are some schemas that we can't generate natively in Python, but we can get from other SDKs in the form of schema protos, and we need to be able to handle them. (For example, the millis_instant type that @Abacn just added).



##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]
+
+SCHEMA_TYPES_TO_STRATEGY = {
+    str: st.text(),
+    bytes: st.binary(),
+    # Maximum datetime on year 3000 to conform to Windows OS limits.
+    Timestamp: st.datetimes(
+        min_value=datetime(1970, 1, 1, 1, 1),
+        max_value=datetime(
+            3000, 1, 1, 0,
+            0)).map(lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
+    int: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
+    np.int64: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
+    np.uint64: st.integers(min_value=0, max_value=1 << 64 - 1),
+    bool: st.booleans()
+}
+
+# A hypothesis strategy that generates schemas.
+# A schema is a list containing tuples of strings (field names), types (field
+# types) and boolean (nullable or not).
+# This strategy currently generates rows with simple types (i.e. non-list, and
+# non-map fields).
+SCHEMA_GENERATOR_STRATEGY = st.lists(
+    st.tuples(
+        st.text(ascii_letters + digits + '_', min_size=1),
+        st.sampled_from(SCHEMA_TYPES),
+        st.booleans()))
+
+
+class ProperyTestingCoders(unittest.TestCase):
+  @given(st.text())
+  def test_string_coder(self, txt: str):
+    coder = StrUtf8Coder()
+    self.assertEqual(coder.decode(coder.encode(txt)), txt)
+
+  @given(st.floats())
+  def test_float_coder(self, num: float):
+    coder = FloatCoder()
+    test_num = coder.decode(coder.encode(num))
+    if math.isnan(num):
+      # This special branch is needed because by definition
+      # nan != nan.
+      self.assertTrue(math.isnan(test_num))
+    else:
+      self.assertEqual(coder.decode(coder.encode(num)), num)
+
+  @settings(deadline=None, print_blob=True)
+  @given(st.data())
+  def test_row_coder(self, data: st.DataObject):
+    """Generate rows and schemas, and test their encoding/decoding.
+
+    The schemas are generated based on the SCHEMA_GENERATOR_STRATEGY.
+    """
+    schema = data.draw(SCHEMA_GENERATOR_STRATEGY)
+    # Assume that the cardinality of the set of names is the same
+    # as the length of the schema. This means there's no duplicate
+    # names for fields.
+    # If this condition does not hold, then we must not continue the
+    # test.
+    assume(len({name for name, _, _ in schema}) == len(schema))
+    assume(
+        len({n[0]
+             for n, _, _ in schema}.intersection(set(digits + '_'))) == 0)
+    RowType = typing.NamedTuple(  # type: ignore
+        'RandomRowType',
+        [(name, type_ if not nullable else typing.Optional[type_]) for name,
+         type_,
+         nullable in schema])
+    coders_registry.register_coder(RowType, RowCoder)
+
+    # TODO(pabloem): Also apply nullability for these schemas.

Review Comment:
   Please file an issue and link here. We should also consider testing the structured types (list, map, nested row, ...) https://github.com/apache/beam/blob/149ed074428ff9b5344169da7d54e8ee271aaba1/model/pipeline/src/main/proto/org/apache/beam/model/pipeline/v1/schema.proto#L68-L72
   
   That could be part of the same issue or another issue



##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]
+
+SCHEMA_TYPES_TO_STRATEGY = {
+    str: st.text(),
+    bytes: st.binary(),
+    # Maximum datetime on year 3000 to conform to Windows OS limits.
+    Timestamp: st.datetimes(
+        min_value=datetime(1970, 1, 1, 1, 1),
+        max_value=datetime(
+            3000, 1, 1, 0,
+            0)).map(lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
+    int: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
+    np.int64: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
+    np.uint64: st.integers(min_value=0, max_value=1 << 64 - 1),
+    bool: st.booleans()
+}
+
+# A hypothesis strategy that generates schemas.
+# A schema is a list containing tuples of strings (field names), types (field
+# types) and boolean (nullable or not).
+# This strategy currently generates rows with simple types (i.e. non-list, and
+# non-map fields).
+SCHEMA_GENERATOR_STRATEGY = st.lists(
+    st.tuples(
+        st.text(ascii_letters + digits + '_', min_size=1),
+        st.sampled_from(SCHEMA_TYPES),
+        st.booleans()))
+
+
+class ProperyTestingCoders(unittest.TestCase):
+  @given(st.text())
+  def test_string_coder(self, txt: str):
+    coder = StrUtf8Coder()
+    self.assertEqual(coder.decode(coder.encode(txt)), txt)
+
+  @given(st.floats())
+  def test_float_coder(self, num: float):
+    coder = FloatCoder()
+    test_num = coder.decode(coder.encode(num))
+    if math.isnan(num):
+      # This special branch is needed because by definition
+      # nan != nan.
+      self.assertTrue(math.isnan(test_num))
+    else:
+      self.assertEqual(coder.decode(coder.encode(num)), num)
+
+  @settings(deadline=None, print_blob=True)
+  @given(st.data())
+  def test_row_coder(self, data: st.DataObject):
+    """Generate rows and schemas, and test their encoding/decoding.
+
+    The schemas are generated based on the SCHEMA_GENERATOR_STRATEGY.
+    """
+    schema = data.draw(SCHEMA_GENERATOR_STRATEGY)
+    # Assume that the cardinality of the set of names is the same
+    # as the length of the schema. This means there's no duplicate
+    # names for fields.
+    # If this condition does not hold, then we must not continue the
+    # test.
+    assume(len({name for name, _, _ in schema}) == len(schema))
+    assume(
+        len({n[0]
+             for n, _, _ in schema}.intersection(set(digits + '_'))) == 0)
+    RowType = typing.NamedTuple(  # type: ignore
+        'RandomRowType',
+        [(name, type_ if not nullable else typing.Optional[type_]) for name,
+         type_,
+         nullable in schema])
+    coders_registry.register_coder(RowType, RowCoder)
+
+    # TODO(pabloem): Also apply nullability for these schemas.
+    row = RowType(  # type: ignore
+        **{
+            name: data.draw(SCHEMA_TYPES_TO_STRATEGY[type_])
+            for name,
+            type_,
+            nullable in schema
+        })
+
+    expected_coder = RowCoder(typing_to_runner_api(RowType).row_type.schema)
+    real_coder = coders_registry.get_coder(RowType)
+    self.assertEqual(expected_coder.decode(expected_coder.encode(row)), row)
+    self.assertEqual(real_coder.decode(real_coder.encode(row)), row)
+    self.assertEqual(real_coder.encode(row), expected_coder.encode(row))

Review Comment:
   If you drop this you won't need to add RowType to the registry either.



##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]
+
+SCHEMA_TYPES_TO_STRATEGY = {
+    str: st.text(),
+    bytes: st.binary(),
+    # Maximum datetime on year 3000 to conform to Windows OS limits.
+    Timestamp: st.datetimes(
+        min_value=datetime(1970, 1, 1, 1, 1),
+        max_value=datetime(
+            3000, 1, 1, 0,
+            0)).map(lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
+    int: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
+    np.int64: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
+    np.uint64: st.integers(min_value=0, max_value=1 << 64 - 1),
+    bool: st.booleans()
+}
+
+# A hypothesis strategy that generates schemas.
+# A schema is a list containing tuples of strings (field names), types (field
+# types) and boolean (nullable or not).
+# This strategy currently generates rows with simple types (i.e. non-list, and
+# non-map fields).
+SCHEMA_GENERATOR_STRATEGY = st.lists(
+    st.tuples(
+        st.text(ascii_letters + digits + '_', min_size=1),
+        st.sampled_from(SCHEMA_TYPES),
+        st.booleans()))
+
+
+class ProperyTestingCoders(unittest.TestCase):
+  @given(st.text())
+  def test_string_coder(self, txt: str):
+    coder = StrUtf8Coder()
+    self.assertEqual(coder.decode(coder.encode(txt)), txt)
+
+  @given(st.floats())
+  def test_float_coder(self, num: float):
+    coder = FloatCoder()
+    test_num = coder.decode(coder.encode(num))
+    if math.isnan(num):
+      # This special branch is needed because by definition
+      # nan != nan.
+      self.assertTrue(math.isnan(test_num))
+    else:
+      self.assertEqual(coder.decode(coder.encode(num)), num)
+
+  @settings(deadline=None, print_blob=True)
+  @given(st.data())
+  def test_row_coder(self, data: st.DataObject):
+    """Generate rows and schemas, and test their encoding/decoding.
+
+    The schemas are generated based on the SCHEMA_GENERATOR_STRATEGY.
+    """
+    schema = data.draw(SCHEMA_GENERATOR_STRATEGY)
+    # Assume that the cardinality of the set of names is the same
+    # as the length of the schema. This means there's no duplicate
+    # names for fields.
+    # If this condition does not hold, then we must not continue the
+    # test.
+    assume(len({name for name, _, _ in schema}) == len(schema))
+    assume(
+        len({n[0]
+             for n, _, _ in schema}.intersection(set(digits + '_'))) == 0)
+    RowType = typing.NamedTuple(  # type: ignore
+        'RandomRowType',
+        [(name, type_ if not nullable else typing.Optional[type_]) for name,
+         type_,
+         nullable in schema])
+    coders_registry.register_coder(RowType, RowCoder)
+
+    # TODO(pabloem): Also apply nullability for these schemas.
+    row = RowType(  # type: ignore
+        **{
+            name: data.draw(SCHEMA_TYPES_TO_STRATEGY[type_])
+            for name,
+            type_,
+            nullable in schema
+        })
+
+    expected_coder = RowCoder(typing_to_runner_api(RowType).row_type.schema)
+    real_coder = coders_registry.get_coder(RowType)
+    self.assertEqual(expected_coder.decode(expected_coder.encode(row)), row)
+    self.assertEqual(real_coder.decode(real_coder.encode(row)), row)
+    self.assertEqual(real_coder.encode(row), expected_coder.encode(row))

Review Comment:
   ```suggestion
       coder = RowCoder(typing_to_runner_api(RowType).row_type.schema)
       self.assertEqual(coder.decode(coder.encode(row)), row)
   ```
   
   I don't think we need to replicate the expected_coder/real_coder silliness here. That was just me being overly cautious to make sure the registration works.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961312058


##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]
+
+SCHEMA_TYPES_TO_STRATEGY = {
+    str: st.text(),
+    bytes: st.binary(),
+    # Maximum datetime on year 3000 to conform to Windows OS limits.
+    Timestamp: st.datetimes(
+        min_value=datetime(1970, 1, 1, 1, 1),
+        max_value=datetime(
+            3000, 1, 1, 0,
+            0)).map(lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
+    int: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
+    np.int64: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
+    np.uint64: st.integers(min_value=0, max_value=1 << 64 - 1),
+    bool: st.booleans()
+}
+
+# A hypothesis strategy that generates schemas.
+# A schema is a list containing tuples of strings (field names), types (field
+# types) and boolean (nullable or not).
+# This strategy currently generates rows with simple types (i.e. non-list, and
+# non-map fields).
+SCHEMA_GENERATOR_STRATEGY = st.lists(
+    st.tuples(
+        st.text(ascii_letters + digits + '_', min_size=1),
+        st.sampled_from(SCHEMA_TYPES),
+        st.booleans()))
+
+
+class ProperyTestingCoders(unittest.TestCase):
+  @given(st.text())
+  def test_string_coder(self, txt: str):
+    coder = StrUtf8Coder()
+    self.assertEqual(coder.decode(coder.encode(txt)), txt)
+
+  @given(st.floats())
+  def test_float_coder(self, num: float):
+    coder = FloatCoder()
+    test_num = coder.decode(coder.encode(num))
+    if math.isnan(num):
+      # This special branch is needed because by definition
+      # nan != nan.
+      self.assertTrue(math.isnan(test_num))
+    else:
+      self.assertEqual(coder.decode(coder.encode(num)), num)
+
+  @settings(deadline=None, print_blob=True)
+  @given(st.data())
+  def test_row_coder(self, data: st.DataObject):
+    """Generate rows and schemas, and test their encoding/decoding.
+
+    The schemas are generated based on the SCHEMA_GENERATOR_STRATEGY.
+    """
+    schema = data.draw(SCHEMA_GENERATOR_STRATEGY)
+    # Assume that the cardinality of the set of names is the same
+    # as the length of the schema. This means there's no duplicate
+    # names for fields.
+    # If this condition does not hold, then we must not continue the
+    # test.
+    assume(len({name for name, _, _ in schema}) == len(schema))
+    assume(
+        len({n[0]
+             for n, _, _ in schema}.intersection(set(digits + '_'))) == 0)
+    RowType = typing.NamedTuple(  # type: ignore
+        'RandomRowType',
+        [(name, type_ if not nullable else typing.Optional[type_]) for name,
+         type_,
+         nullable in schema])
+    coders_registry.register_coder(RowType, RowCoder)
+
+    # TODO(pabloem): Also apply nullability for these schemas.

Review Comment:
   aadded to the same issue



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] pabloem commented on a diff in pull request #22233: Trying out property-based tests for Beam python coders

Posted by GitBox <gi...@apache.org>.
pabloem commented on code in PR #22233:
URL: https://github.com/apache/beam/pull/22233#discussion_r961310967


##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]

Review Comment:
   Thanks! I've added the check for the primitives, but not for logical types. I created https://github.com/apache/beam/issues/23003 to track that.



##########
sdks/python/apache_beam/coders/coders_property_based_test.py:
##########
@@ -0,0 +1,138 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Property tests for coders in the Python SDK.
+
+The tests in this file utilize the hypothesis library to generate random test
+cases and run them against Beam's coder implementations.
+
+These tests are similar to fuzzing, except they test invariant properties
+of code.
+"""
+
+import math
+import typing
+import unittest
+# TODO(pabloem): Include other categories of characters
+from datetime import datetime
+from string import ascii_letters
+from string import digits
+
+import numpy as np
+from hypothesis import strategies as st
+from hypothesis import assume
+from hypothesis import given
+from hypothesis import settings
+from pytz import utc
+
+from apache_beam.coders import FloatCoder
+from apache_beam.coders import RowCoder
+from apache_beam.coders import StrUtf8Coder
+from apache_beam.coders.typecoders import registry as coders_registry
+from apache_beam.typehints.schemas import typing_to_runner_api
+from apache_beam.utils.timestamp import Timestamp
+
+SCHEMA_TYPES = [str, bytes, Timestamp, int, np.int32, np.int64, bool]
+
+SCHEMA_TYPES_TO_STRATEGY = {
+    str: st.text(),
+    bytes: st.binary(),
+    # Maximum datetime on year 3000 to conform to Windows OS limits.
+    Timestamp: st.datetimes(
+        min_value=datetime(1970, 1, 1, 1, 1),
+        max_value=datetime(
+            3000, 1, 1, 0,
+            0)).map(lambda dt: Timestamp.from_utc_datetime(dt.astimezone(utc))),
+    int: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.int32: st.integers(min_value=-(1 << 31 - 1), max_value=1 << 31 - 1),
+    np.int64: st.integers(min_value=-(1 << 63 - 1), max_value=1 << 63 - 1),
+    np.uint32: st.integers(min_value=0, max_value=1 << 32 - 1),
+    np.uint64: st.integers(min_value=0, max_value=1 << 64 - 1),

Review Comment:
   hm well, since they work I'll leave them there : )



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org