TheNeuralBit commented on a change in pull request #12819:
URL: https://github.com/apache/beam/pull/12819#discussion_r493930520



##########
File path: sdks/python/apache_beam/dataframe/pandas_docs_test.py
##########
@@ -0,0 +1,90 @@
+#
+# 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.
+
+"""A module for running the pandas docs (such as the users guide) against our
+dataframe implementation.
+
+Run as python -m apache_beam.dataframe.pandas_docs_test [getting_started ...]
+"""
+
+from __future__ import absolute_import
+from __future__ import print_function
+
+import os
+import sys
+import zipfile
+
+from apache_beam.dataframe import doctests
+
+PANDAS_VERSION = '1.1.1'
+PANDAS_DIR = os.path.expanduser("~/.apache_beam/cache/pandas-" + 
PANDAS_VERSION)
+PANDAS_DOCS_SOURCE = os.path.join(PANDAS_DIR, 'doc', 'source')
+
+
+def main():
+  # Not available for Python 2.
+  import urllib.request
+  if not os.path.exists(PANDAS_DIR):
+    # Download the pandas source.
+    os.makedirs(os.path.dirname(PANDAS_DIR), exist_ok=True)
+    zip = os.path.join(PANDAS_DIR + '.zip')
+    if not os.path.exists(zip):
+      url = (
+          'https://github.com/pandas-dev/pandas/archive/v%s.zip' %
+          PANDAS_VERSION)
+      print('Downloading', url)
+      with urllib.request.urlopen(url) as fin:
+        with open(zip, 'wb') as fout:
+          fout.write(fin.read())
+
+    print('Extrating', zip)

Review comment:
       ```suggestion
       print('Extracting', zip)
   ```

##########
File path: sdks/python/apache_beam/dataframe/doctests.py
##########
@@ -428,7 +482,106 @@ def print_partition(indent, desc, n, total):
     print()
 
 
-def teststring(text, report=True, **runner_kwargs):
+def parse_rst_ipython_tests(rst, name, extraglobs=None, optionflags=None):
+  """Extracts examples from an rst file and produce a test suite by running
+  them through pandas to get the expected outputs.
+  """
+
+  # Optional dependency.
+  import IPython
+  from traitlets.config import Config
+
+  def get_indent(line):
+    return len(line) - len(line.lstrip())
+
+  def is_example_line(line):
+    line = line.strip()
+    return line and not line.startswith('#') and not line[0] == line[-1] == ':'
+
+  IMPORT_PANDAS = 'import pandas as pd'
+
+  example_srcs = []
+  lines = iter(
+      [line.rstrip()
+       for line in rst.split('\n') if is_example_line(line)] + ['END'])
+
+  # https://ipython.readthedocs.io/en/stable/sphinxext.html
+  for line in lines:
+    if line.startswith('.. ipython::'):
+      line = next(lines)
+      indent = get_indent(line)
+      example = []
+      example_srcs.append(example)
+      while get_indent(line) >= indent:
+        if '@verbatim' in line or '@savefig' in line:

Review comment:
       We should probably check for `:verbatim:` 
https://ipython.readthedocs.io/en/stable/sphinxext.html#pseudo-decorators

##########
File path: sdks/python/apache_beam/dataframe/doctests_test.py
##########
@@ -77,6 +77,46 @@
 failed exception
 '''
 
+RST_IPYTHON = '''
+Here is an example
+.. ipython::
+
+    2 + 2
+
+and a multi-line example
+
+.. ipython::
+
+    def foo(x):
+        return x * x
+    foo(4)
+
+history is preserved
+
+    foo(3)
+    foo(4)
+
+and finally an example with pandas
+
+.. ipython::
+
+    pd.Series([1, 2, 3]).max()
+
+
+This one should be skipped:
+
+.. ipython::
+
+   @verbatim
+   not run or tested
+
+and someting that'll fail (due to fake vs. read pandas)

Review comment:
       ```suggestion
   and someting that'll fail (due to fake vs. real pandas)
   ```

##########
File path: sdks/python/apache_beam/runners/direct/evaluation_context.py
##########
@@ -102,7 +102,8 @@ def __init__(self, side_inputs):
         list
     )  # type: DefaultDict[Optional[AppliedPTransform], 
List[pvalue.AsSideInput]]
     # this appears unused:
-    self._side_input_to_blocked_tasks = collections.defaultdict(list)  # type: 
ignore
+    self._side_input_to_blocked_tasks = collections.defaultdict(
+        list)  # type: ignore

Review comment:
       Would be good to drop this unrelated change

##########
File path: sdks/python/apache_beam/dataframe/doctests.py
##########
@@ -350,16 +355,57 @@ def fake_pandas_module(self):
 
   def summarize(self):
     super(BeamDataframeDoctestRunner, self).summarize()
+    self.summary().summarize()
 
+  def summary(self):
+    return Summary(
+        self.failures,
+        self.tries,
+        self.skipped,
+        self.wont_implement,
+        self._wont_implement_reasons)
+
+
+class AugmentedTestResults(doctest.TestResults):
+  pass
+
+
+class Summary(object):
+  def __init__(
+      self,
+      failures=0,
+      tries=0,
+      skipped=0,
+      wont_implement=0,
+      wont_implement_reasons=None):
+    self.failures = failures
+    self.tries = tries
+    self.skipped = skipped
+    self.wont_implement = wont_implement
+    self.wont_implement_reasons = wont_implement_reasons or []
+
+  def __add__(self, other):
+    return Summary(
+        self.failures + other.failures,
+        self.tries + other.tries,
+        self.skipped + other.skipped,
+        self.wont_implement + other.wont_implement,
+        self.wont_implement_reasons + other.wont_implement_reasons)

Review comment:
       Nice, we should use this to aggregate pandas_doctests_test too

##########
File path: sdks/python/apache_beam/dataframe/pandas_docs_test.py
##########
@@ -0,0 +1,91 @@
+#
+# 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.
+
+"""A module for running the pandas docs (such as the users guide) against our
+dataframe implementation.
+
+Run as python -m apache_beam.dataframe.pandas_docs_test [getting_started ...]
+"""
+
+from __future__ import absolute_import
+from __future__ import print_function
+
+import os
+import sys
+import zipfile
+
+from apache_beam.dataframe import doctests
+
+PANDAS_VERSION = '1.1.1'
+PANDAS_DIR = os.path.expanduser("~/.apache_beam/cache/pandas-" + 
PANDAS_VERSION)
+PANDAS_DOCS_SOURCE = os.path.join(PANDAS_DIR, 'doc', 'source')
+
+
+def main():
+  # Not available for Python 2.
+  import urllib.request
+  if not os.path.exists(PANDAS_DIR):
+    # Download the pandas source.
+    os.makedirs(os.path.dirname(PANDAS_DIR), exist_ok=True)
+    zip = os.path.join(PANDAS_DIR + '.zip')
+    if not os.path.exists(zip):
+      url = (
+          'https://github.com/pandas-dev/pandas/archive/v%s.zip' %
+          PANDAS_VERSION)
+      print('Downloading', url)
+      with urllib.request.urlopen(url) as fin:
+        with open(zip + '.tmp', 'wb') as fout:
+          fout.write(fin.read())
+        os.rename(zip + '.tmp', zip)
+
+    print('Extrating', zip)
+    with zipfile.ZipFile(zip, 'r') as handle:
+      handle.extractall(os.path.dirname(PANDAS_DIR))
+
+  tests = sys.argv[1:] or ['getting_started', 'user_guide']
+  paths = []
+  filters = []
+
+  # Explicit paths.
+  for test in tests:
+    if os.path.exists(test):
+      paths.append(test)
+    else:
+      filters.append(test)
+
+  # Names of pandas source files.
+  for root, _, files in os.walk(PANDAS_DOCS_SOURCE):
+    for name in files:
+      if name.endswith('.rst'):
+        path = os.path.join(root, name)
+        if any(filter in path for filter in filters):
+          paths.append(path)
+
+  # Now run all the tests.
+  running_summary = doctests.Summary()
+  for path in paths:
+    with open(path) as f:
+      rst = f.read()
+    running_summary += doctests.test_rst_ipython(
+        rst, path, report=True, wont_implement_ok=['*'], 
use_beam=False).summary

Review comment:
       If doctests supported it would we want this to allow WontImplement and 
NotImplemented?

##########
File path: sdks/python/apache_beam/dataframe/doctests.py
##########
@@ -428,7 +482,106 @@ def print_partition(indent, desc, n, total):
     print()
 
 
-def teststring(text, report=True, **runner_kwargs):
+def parse_rst_ipython_tests(rst, name, extraglobs=None, optionflags=None):
+  """Extracts examples from an rst file and produce a test suite by running
+  them through pandas to get the expected outputs.
+  """
+
+  # Optional dependency.
+  import IPython
+  from traitlets.config import Config
+
+  def get_indent(line):
+    return len(line) - len(line.lstrip())
+
+  def is_example_line(line):
+    line = line.strip()
+    return line and not line.startswith('#') and not line[0] == line[-1] == ':'
+
+  IMPORT_PANDAS = 'import pandas as pd'
+
+  example_srcs = []
+  lines = iter(
+      [line.rstrip()
+       for line in rst.split('\n') if is_example_line(line)] + ['END'])
+
+  # https://ipython.readthedocs.io/en/stable/sphinxext.html
+  for line in lines:
+    if line.startswith('.. ipython::'):
+      line = next(lines)
+      indent = get_indent(line)
+      example = []
+      example_srcs.append(example)
+      while get_indent(line) >= indent:
+        if '@verbatim' in line or '@savefig' in line:
+          example_srcs.pop()
+          break
+        example.append(line[indent:])
+        line = next(lines)
+        if get_indent(line) == indent:
+          example = []
+          example_srcs.append(example)

Review comment:
       Are you sure this is never consuming the start of another example? It 
looks like rst may require a blank line after a `.. ipython::` block, but I 
just wanted to check that something like this wont happen:
   
   ```
   .. ipython::
     df = ..
   .. ipython::
     df
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to