Apache DataFusion SQL Query Engine
ARROW-394: [Integration] Generate tests cases for numeric types, strings, lists, structs
Wes McKinney5f8d7cf7ce71
diff --git a/.travis.yml b/.travis.ymlindex bfc2f26b4f..1634eba443 100644--- a/.travis.yml+++ b/.travis.yml@@ -46,6 +46,16 @@ matrix:jdk: oraclejdk7script:- $TRAVIS_BUILD_DIR/ci/travis_script_java.sh+ - language: java+ os: linux+ env: ARROW_TEST_GROUP=integration+ jdk: oraclejdk7+ before_script:+ - export CC="gcc-4.9"+ - export CXX="g++-4.9"+ - $TRAVIS_BUILD_DIR/ci/travis_before_script_cpp.sh+ script:+ - $TRAVIS_BUILD_DIR/ci/travis_script_integration.shbefore_install:- ulimit -c unlimited -Sdiff --git a/ci/travis_script_integration.sh b/ci/travis_script_integration.shnew file mode 100755index 0000000000..d93411b907--- /dev/null+++ b/ci/travis_script_integration.sh@@ -0,0 +1,49 @@+#!/usr/bin/env bash++# Licensed 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. See accompanying LICENSE file.++set -e++: ${CPP_BUILD_DIR=$TRAVIS_BUILD_DIR/cpp-build}++JAVA_DIR=${TRAVIS_BUILD_DIR}/java++pushd $JAVA_DIR++mvn package++popd++pushd $TRAVIS_BUILD_DIR/integration++VERSION=0.1.1-SNAPSHOT+export ARROW_JAVA_INTEGRATION_JAR=$JAVA_DIR/tools/target/arrow-tools-$VERSION-jar-with-dependencies.jar+export ARROW_CPP_TESTER=$CPP_BUILD_DIR/debug/json-integration-test++source $TRAVIS_BUILD_DIR/ci/travis_install_conda.sh+export MINICONDA=$HOME/miniconda+export PATH="$MINICONDA/bin:$PATH"++CONDA_ENV_NAME=arrow-integration-test+conda create -y -q -n $CONDA_ENV_NAME python=3.5+source activate $CONDA_ENV_NAME++# faster builds, please+conda install -y nomkl++# Expensive dependencies install from Continuum package repo+conda install -y pip numpy six++python integration_test.py --debug++popddiff --git a/integration/README.md b/integration/README.mdnew file mode 100644index 0000000000..b1e4e3a82a--- /dev/null+++ b/integration/README.md@@ -0,0 +1,59 @@+<!---+ Licensed 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. See accompanying LICENSE file.+-->++# Arrow integration testing++Our strategy for integration testing between Arrow implementations is as follows:++* Test datasets are specified in a custom human-readable, JSON-based format+ designed for Arrow++* Each implementation provides a testing executable capable of converting+ between the JSON and the binary Arrow file representation++* The test executable is also capable of validating the contents of a binary+ file against a corresponding JSON file++## Running the existing integration tests++First, build the Java and C++ projects. For Java, you must run++```+mvn package+```++Now, the integration tests rely on two environment variables which point to the+Java `arrow-tool` JAR and the C++ `json-integration-test` executable:++```bash+JAVA_DIR=$ARROW_HOME/java+CPP_BUILD_DIR=$ARROW_HOME/cpp/test-build++VERSION=0.1.1-SNAPSHOT+export ARROW_JAVA_INTEGRATION_JAR=$JAVA_DIR/tools/target/arrow-tools-$VERSION-jar-with-dependencies.jar+export ARROW_CPP_TESTER=$CPP_BUILD_DIR/debug/json-integration-test+```++Here `$ARROW_HOME` is the location of your Arrow git clone. The+`$CPP_BUILD_DIR` may be different depending on how you built with CMake+(in-source of out-of-source).++Once this is done, run the integration tests with (optionally adding `--debug`+for additional output)++```+python integration_test.py++python integration_test.py --debug # additional output+```\ No newline at end of filediff --git a/integration/integration_test.py b/integration/integration_test.pyindex 88dc3ad797..417354bc83 100644--- a/integration/integration_test.py+++ b/integration/integration_test.py@@ -15,23 +15,53 @@# specific language governing permissions and limitations# under the License.+from collections import OrderedDictimport argparseimport globimport itertools+import jsonimport osimport six+import stringimport subprocessimport tempfileimport uuid+import numpy as npARROW_HOME = os.path.abspath(__file__).rsplit("/", 2)[0]+# Control for flakiness+np.random.seed(12345)+def guid():return uuid.uuid4().hex+# from pandas+RANDS_CHARS = np.array(list(string.ascii_letters + string.digits),+ dtype=(np.str_, 1))+++def rands(nchars):+ """+ Generate one random byte string.++ See `rands_array` if you want to create an array of random strings.++ """+ return ''.join(np.random.choice(RANDS_CHARS, nchars))+++def str_from_bytes(x):+ if six.PY2:+ return x+ else:+ return x.decode('utf-8')+++# from the merge_arrow_pr.py scriptdef run_cmd(cmd):if isinstance(cmd, six.string_types):cmd = cmd.split(' ')@@ -43,13 +73,469 @@ def run_cmd(cmd):print('Command failed: %s' % ' '.join(cmd))print('With output:')print('--------------')- print(e.output)+ print(str_from_bytes(e.output))print('--------------')raise e- if isinstance(output, six.binary_type):- output = output.decode('utf-8')- return output+ return str_from_bytes(output)++# ----------------------------------------------------------------------+# Data generation+++class DataType(object):++ def __init__(self, name, nullable=True):+ self.name = name+ self.nullable = nullable++ def get_json(self):+ return OrderedDict([+ ('name', self.name),+ ('type', self._get_type()),+ ('nullable', self.nullable),+ ('children', self._get_children()),+ ('typeLayout', self._get_type_layout())+ ])++ def _make_is_valid(self, size):+ if self.nullable:+ return np.random.randint(0, 2, size=size)+ else:+ return np.ones(size)+++class Column(object):++ def __init__(self, name, count):+ self.name = name+ self.count = count++ def _get_children(self):+ return []++ def _get_buffers(self):+ return []++ def get_json(self):+ entries = [+ ('name', self.name),+ ('count', self.count)+ ]++ buffers = self._get_buffers()+ entries.extend(buffers)++ children = self._get_children()+ if len(children) > 0:+ entries.append(('children', children))++ return OrderedDict(entries)+++class PrimitiveType(DataType):++ def _get_children(self):+ return []++ def _get_type_layout(self):+ return OrderedDict([+ ('vectors',+ [OrderedDict([('type', 'VALIDITY'),+ ('typeBitWidth', 1)]),+ OrderedDict([('type', 'DATA'),+ ('typeBitWidth', self.bit_width)])])])+++class PrimitiveColumn(Column):++ def __init__(self, name, count, is_valid, values):+ Column.__init__(self, name, count)+ self.is_valid = is_valid+ self.values = values++ def _get_buffers(self):+ return [+ ('VALIDITY', [int(v) for v in self.is_valid]),+ ('DATA', list(self.values))+ ]+++TEST_INT_MIN = - 2**31 + 1+TEST_INT_MAX = 2**31 - 1+++class IntegerType(PrimitiveType):++ def __init__(self, name, is_signed, bit_width, nullable=True):+ PrimitiveType.__init__(self, name, nullable=nullable)+ self.is_signed = is_signed+ self.bit_width = bit_width++ @property+ def numpy_type(self):+ return ('int' if self.is_signed else 'uint') + str(self.bit_width)++ def _get_type(self):+ return OrderedDict([+ ('name', 'int'),+ ('isSigned', self.is_signed),+ ('bitWidth', self.bit_width)+ ])++ def generate_column(self, size):+ iinfo = np.iinfo(self.numpy_type)+ values = [int(x) for x in+ np.random.randint(max(iinfo.min, TEST_INT_MIN),+ min(iinfo.max, TEST_INT_MAX),+ size=size)]++ is_valid = self._make_is_valid(size)+ return PrimitiveColumn(self.name, size, is_valid, values)+++class FloatingPointType(PrimitiveType):++ def __init__(self, name, bit_width, nullable=True):+ PrimitiveType.__init__(self, name, nullable=nullable)++ self.bit_width = bit_width+ self.precision = {+ 16: 'HALF',+ 32: 'SINGLE',+ 64: 'DOUBLE'+ }[self.bit_width]++ @property+ def numpy_type(self):+ return 'float' + str(self.bit_width)++ def _get_type(self):+ return OrderedDict([+ ('name', 'floatingpoint'),+ ('precision', self.precision)+ ])++ def generate_column(self, size):+ values = np.random.randn(size) * 1000+ values = np.round(values, 3)++ is_valid = self._make_is_valid(size)+ return PrimitiveColumn(self.name, size, is_valid, values)+++class BooleanType(PrimitiveType):++ bit_width = 1++ def _get_type(self):+ return OrderedDict([('name', 'bool')])++ @property+ def numpy_type(self):+ return 'bool'++ def generate_column(self, size):+ values = list(map(bool, np.random.randint(0, 2, size=size)))+ is_valid = self._make_is_valid(size)+ return PrimitiveColumn(self.name, size, is_valid, values)+++class StringType(PrimitiveType):++ @property+ def numpy_type(self):+ return object++ def _get_type(self):+ return OrderedDict([('name', 'utf8')])++ def _get_type_layout(self):+ return OrderedDict([+ ('vectors',+ [OrderedDict([('type', 'VALIDITY'),+ ('typeBitWidth', 1)]),+ OrderedDict([('type', 'OFFSET'),+ ('typeBitWidth', 32)]),+ OrderedDict([('type', 'DATA'),+ ('typeBitWidth', 8)])])])++ def generate_column(self, size):+ K = 7+ is_valid = self._make_is_valid(size)+ values = []++ for i in range(size):+ if is_valid[i]:+ values.append(rands(K))+ else:+ values.append("")++ return StringColumn(self.name, size, is_valid, values)+++class JSONSchema(object):++ def __init__(self, fields):+ self.fields = fields++ def get_json(self):+ return OrderedDict([+ ('fields', [field.get_json() for field in self.fields])+ ])+++class StringColumn(PrimitiveColumn):++ def _get_buffers(self):+ offset = 0+ offsets = [0]++ data = []+ for i, v in enumerate(self.values):+ if self.is_valid[i]:+ offset += len(v)+ else:+ v = ""++ offsets.append(offset)+ data.append(v)++ return [+ ('VALIDITY', [int(x) for x in self.is_valid]),+ ('OFFSET', offsets),+ ('DATA', data)+ ]+++class ListType(DataType):++ def __init__(self, name, value_type, nullable=True):+ DataType.__init__(self, name, nullable=nullable)+ self.value_type = value_type++ def _get_type(self):+ return OrderedDict([+ ('name', 'list')+ ])++ def _get_children(self):+ return [self.value_type.get_json()]++ def _get_type_layout(self):+ return OrderedDict([+ ('vectors',+ [OrderedDict([('type', 'VALIDITY'),+ ('typeBitWidth', 1)]),+ OrderedDict([('type', 'OFFSET'),+ ('typeBitWidth', 32)])])])++ def generate_column(self, size):+ MAX_LIST_SIZE = 4++ is_valid = self._make_is_valid(size)+ list_sizes = np.random.randint(0, MAX_LIST_SIZE + 1, size=size)+ offsets = [0]++ offset = 0+ for i in range(size):+ if is_valid[i]:+ offset += int(list_sizes[i])+ offsets.append(offset)++ # The offset now is the total number of elements in the child array+ values = self.value_type.generate_column(offset)++ return ListColumn(self.name, size, is_valid, offsets, values)+++class ListColumn(Column):++ def __init__(self, name, count, is_valid, offsets, values):+ Column.__init__(self, name, count)+ self.is_valid = is_valid+ self.offsets = offsets+ self.values = values++ def _get_buffers(self):+ return [+ ('VALIDITY', [int(v) for v in self.is_valid]),+ ('OFFSET', list(self.offsets))+ ]++ def _get_children(self):+ return [self.values.get_json()]+++class StructType(DataType):++ def __init__(self, name, field_types, nullable=True):+ DataType.__init__(self, name, nullable=nullable)+ self.field_types = field_types++ def _get_type(self):+ return OrderedDict([+ ('name', 'struct')+ ])++ def _get_children(self):+ return [type_.get_json() for type_ in self.field_types]++ def _get_type_layout(self):+ return OrderedDict([+ ('vectors',+ [OrderedDict([('type', 'VALIDITY'),+ ('typeBitWidth', 1)])])])++ def generate_column(self, size):+ is_valid = self._make_is_valid(size)++ field_values = [type_.generate_column(size)+ for type_ in self.field_types]++ return StructColumn(self.name, size, is_valid, field_values)+++class StructColumn(Column):++ def __init__(self, name, count, is_valid, field_values):+ Column.__init__(self, name, count)+ self.is_valid = is_valid+ self.field_values = field_values++ def _get_buffers(self):+ return [+ ('VALIDITY', [int(v) for v in self.is_valid])+ ]++ def _get_children(self):+ return [field.get_json() for field in self.field_values]+++class JSONRecordBatch(object):++ def __init__(self, count, columns):+ self.count = count+ self.columns = columns++ def get_json(self):+ return OrderedDict([+ ('count', self.count),+ ('columns', [col.get_json() for col in self.columns])+ ])+++class JSONFile(object):++ def __init__(self, schema, batches):+ self.schema = schema+ self.batches = batches++ def get_json(self):+ return OrderedDict([+ ('schema', self.schema.get_json()),+ ('batches', [batch.get_json() for batch in self.batches])+ ])++ def write(self, path):+ with open(path, 'wb') as f:+ f.write(json.dumps(self.get_json(), indent=2).encode('utf-8'))+++def get_field(name, type_, nullable=True):+ if type_ == 'utf8':+ return StringType(name, nullable=nullable)++ dtype = np.dtype(type_)++ if dtype.kind in ('i', 'u'):+ return IntegerType(name, dtype.kind == 'i', dtype.itemsize * 8,+ nullable=nullable)+ elif dtype.kind == 'f':+ return FloatingPointType(name, dtype.itemsize * 8,+ nullable=nullable)+ elif dtype.kind == 'b':+ return BooleanType(name, nullable=nullable)+ else:+ raise TypeError(dtype)+++def generate_primitive_case():+ types = ['bool', 'int8', 'int16', 'int32', 'int64',+ 'uint8', 'uint16', 'uint32', 'uint64',+ 'float32', 'float64', 'utf8']++ fields = []++ for type_ in types:+ fields.append(get_field(type_ + "_nullable", type_, True))+ fields.append(get_field(type_ + "_nonnullable", type_, False))++ schema = JSONSchema(fields)++ batch_sizes = [7, 10]+ batches = []+ for size in batch_sizes:+ columns = []+ for field in fields:+ col = field.generate_column(size)+ columns.append(col)++ batches.append(JSONRecordBatch(size, columns))++ return JSONFile(schema, batches)+++def generate_nested_case():+ fields = [+ ListType('list_nullable', get_field('item', 'int32')),+ StructType('struct_nullable', [get_field('f1', 'int32'),+ get_field('f2', 'utf8')]),++ # TODO(wesm): this causes segfault+ # ListType('list_nonnullable', get_field('item', 'int32'), False),+ ]++ schema = JSONSchema(fields)++ batch_sizes = [7, 10]+ batches = []+ for size in batch_sizes:+ columns = []+ for field in fields:+ col = field.generate_column(size)+ columns.append(col)++ batches.append(JSONRecordBatch(size, columns))++ return JSONFile(schema, batches)+++def get_generated_json_files():+ temp_dir = tempfile.mkdtemp()++ def _temp_path():+ return++ file_objs = []++ K = 10+ for i in range(K):+ file_objs.append(generate_primitive_case())++ file_objs.append(generate_nested_case())++ generated_paths = []+ for file_obj in file_objs:+ out_path = os.path.join(temp_dir, guid() + '.json')+ file_obj.write(out_path)+ generated_paths.append(out_path)++ return generated_paths+++# ----------------------------------------------------------------------+# Testing harnessclass IntegrationRunner(object):@@ -92,9 +578,11 @@ class Tester(object):class JavaTester(Tester):- ARROW_TOOLS_JAR = os.path.join(ARROW_HOME,- 'java/tools/target/arrow-tools-0.1.1-'- 'SNAPSHOT-jar-with-dependencies.jar')+ ARROW_TOOLS_JAR = os.environ.get(+ 'ARROW_JAVA_INTEGRATION_JAR',+ os.path.join(ARROW_HOME,+ 'java/tools/target/arrow-tools-0.1.1-'+ 'SNAPSHOT-jar-with-dependencies.jar'))name = 'Java'@@ -154,14 +642,16 @@ class CPPTester(Tester):return self._run(arrow_path, json_path, 'JSON_TO_ARROW')-def get_json_files():+def get_static_json_files():glob_pattern = os.path.join(ARROW_HOME, 'integration', 'data', '*.json')return glob.glob(glob_pattern)def run_all_tests(debug=False):testers = [JavaTester(debug=debug), CPPTester(debug=debug)]- json_files = get_json_files()+ static_json_files = get_static_json_files()+ generated_json_files = get_generated_json_files()+ json_files = static_json_files + generated_json_filesrunner = IntegrationRunner(json_files, testers, debug=debug)runner.run()