Skip to content

Commit 7813ecb

Browse files
committed
Fix tfds testing pylint
1 parent 018322b commit 7813ecb

File tree

13 files changed

+47
-43
lines changed

13 files changed

+47
-43
lines changed

tensorflow_datasets/testing/dataset_builder_testing.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ def _get_dl_download_result(self, url):
256256
return utils.map_nested(lambda fname: os.path.join(self.example_dir, fname),
257257
self.DL_DOWNLOAD_RESULT)
258258

259-
def _download_checksums(self, url):
259+
def _download_checksums(self, _):
260260
self._stop_record_download = True
261261

262262
def _make_builder(self, config=None):
@@ -267,6 +267,7 @@ def _make_builder(self, config=None):
267267

268268
@test_utils.run_in_graph_and_eager_modes()
269269
def test_download_and_prepare_as_dataset(self):
270+
"""Test download and prepare function on fake testing dataset"""
270271
# If configs specified, ensure they are all valid
271272
if self.BUILDER_CONFIG_NAMES_TO_TEST:
272273
for config in self.BUILDER_CONFIG_NAMES_TO_TEST: # pylint: disable=not-an-iterable
@@ -295,7 +296,7 @@ def test_download_and_prepare_as_dataset(self):
295296
self._test_checksums()
296297

297298
def _test_checksums(self):
298-
# If no call to `dl_manager.download`, then no need to check url presence.
299+
"""If no call to `dl_manager.download`, then no need to check url presence"""
299300
if not self._download_urls:
300301
return
301302

@@ -312,13 +313,14 @@ def _test_checksums(self):
312313
self.assertEmpty(
313314
missing_urls,
314315
"Some urls checksums are missing at: {} "
315-
"Did you forgot to record checksums with `--register_checksums` ? "
316+
"Did you forget to record checksums with `--register_checksums` ? "
316317
"See instructions at: "
317318
"https://www.tensorflow.org/datasets/add_dataset#2_run_download_and_prepare_locally"
318319
"\n{}".format(filepath, err_msg)
319320
)
320321

321322
def _download_and_prepare_as_dataset(self, builder):
323+
"""A utility function"""
322324
# Provide the manual dir only if builder has MANUAL_DOWNLOAD_INSTRUCTIONS
323325
# set.
324326

@@ -367,7 +369,7 @@ def _download_and_prepare_as_dataset(self, builder):
367369
with self._subTest("as_dataset"):
368370
self._assertAsDataset(builder_reloaded)
369371

370-
def _assertAsDataset(self, builder):
372+
def _assertAsDataset(self, builder): # pylint: disable = invalid-name, missing-function-docstring
371373
split_to_checksums = {} # {"split": set(examples_checksums)}
372374
for split_name, expected_examples_number in self.SPLITS.items():
373375
ds = builder.as_dataset(split=split_name)
@@ -392,7 +394,7 @@ def _assertAsDataset(self, builder):
392394
"have the same objects in those splits? If yes, add one one of "
393395
"them to OVERLAPPING_SPLITS class attribute.") % (split1, split2))
394396

395-
def _assertNumSamples(self, builder):
397+
def _assertNumSamples(self, builder): # pylint: disable = invalid-name
396398
for split_name, expected_num_examples in self.SPLITS.items():
397399
self.assertEqual(
398400
builder.info.splits[split_name].num_examples,

tensorflow_datasets/testing/fake_data_generation/cifar.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ def dump(output_dir, fname, images, labels):
5858
path = os.path.join(output_dir, fname)
5959
print("Writing %s..." % path)
6060
with open(path, "wb") as out_file:
61-
for image, labels in zip(images, labels):
62-
out_file.write(labels.tobytes())
61+
for image, label in zip(images, labels):
62+
out_file.write(label.tobytes())
6363
out_file.write(image.tobytes())
6464

6565

tensorflow_datasets/testing/fake_data_generation/coil100.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def create_images(label):
5353

5454
def main(argv):
5555
del argv
56-
label = [x for x in range(0, 25, 5)]
56+
label = list(range(0, 25, 5))
5757
create_images(label)
5858

5959

tensorflow_datasets/testing/fake_data_generation/flic.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def _generate_mat(data, train_fname, test_fname):
9393
scipy.io.savemat(dirname, data)
9494

9595

96-
def main(unused_argv):
96+
def main(_):
9797
_generate_image("small", "images", "example_movie00000001.jpg")
9898
_generate_image("small", "images", "example_movie00000002.jpg")
9999
_generate_mat("small", "example_movie00000001.jpg",

tensorflow_datasets/testing/fake_data_generation/lsun.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@
3535

3636
from absl import app
3737
from absl import flags
38-
import lmdb
3938
import tensorflow.compat.v2 as tf
39+
import lmdb
4040

4141
FLAGS = flags.FLAGS
4242

tensorflow_datasets/testing/fake_data_generation/smallnorb_test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030

3131
class SmallnorbTest(parameterized.TestCase):
32+
"""A class for testing Smallnorb dataset"""
3233

3334
@parameterized.named_parameters(
3435
("uint8", np.array([[1, 2, 3], [1, 2, 3]], dtype=np.dtype("|u1"))),

tensorflow_datasets/testing/fake_data_generation/starcraft.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@
3030
from absl import app
3131
from absl import flags
3232
import numpy as np
33-
import png
3433
import six
3534
import tensorflow.compat.v2 as tf
35+
import png
3636

3737
FLAGS = flags.FLAGS
3838

tensorflow_datasets/testing/fake_data_generation/sun397.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@
2828
import tarfile
2929
import tempfile
3030

31+
import md5
3132
from absl import app
3233
from absl import flags
33-
import md5
3434

3535
import numpy as np
3636
from tensorflow_datasets.core.utils import py_utils

tensorflow_datasets/testing/mocking.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,10 @@ def mock_as_dataset(self, *args, **kwargs):
124124
if not data_dir:
125125
data_dir = os.path.join(os.path.dirname(__file__), 'metadata')
126126

127-
download_and_prepare_path = 'tensorflow_datasets.core.dataset_builder.DatasetBuilder.download_and_prepare'
128-
as_dataset_path = 'tensorflow_datasets.core.dataset_builder.FileAdapterBuilder._as_dataset'
127+
download_and_prepare_path = \
128+
'tensorflow_datasets.core.dataset_builder.DatasetBuilder.download_and_prepare'
129+
as_dataset_path = \
130+
'tensorflow_datasets.core.dataset_builder.FileAdapterBuilder._as_dataset'
129131
data_dir_path = 'tensorflow_datasets.core.constants.DATA_DIR'
130132

131133
with absltest.mock.patch(as_dataset_path, as_dataset_fn), \
@@ -135,7 +137,7 @@ def mock_as_dataset(self, *args, **kwargs):
135137
yield
136138

137139

138-
class RandomFakeGenerator(object):
140+
class RandomFakeGenerator():
139141
"""Generator of fake examples randomly and deterministically generated."""
140142

141143
def __init__(self, builder, num_examples, seed=0):
@@ -163,14 +165,13 @@ def _generate_random_array(self, feature, tensor_info):
163165
# Generate some random values, depending on the dtype
164166
if tensor_info.dtype.is_integer:
165167
return self._rgn.randint(0, max_value, shape)
166-
elif tensor_info.dtype.is_floating:
168+
if tensor_info.dtype.is_floating:
167169
return self._rgn.random_sample(shape)
168-
elif tensor_info.dtype == tf.string:
170+
if tensor_info.dtype == tf.string:
169171
return ''.join(
170172
random.choice(' abcdefghij') for _ in range(random.randint(10, 20)))
171-
else:
172-
raise ValueError('Fake generation not supported for {}'.format(
173-
tensor_info.dtype))
173+
raise ValueError('Fake generation not supported for {}'.format(
174+
tensor_info.dtype))
174175

175176
def _generate_example(self):
176177
"""Generate the next example."""

tensorflow_datasets/testing/mocking_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737

3838

3939
class MockingTest(test_case.TestCase):
40-
40+
"""A class for testing tensorflow_datasets.testing.mocking"""
4141
def test_mocking_imagenet(self):
4242
with mocking.mock_data():
4343
ds = registered.load('imagenet2012', split='train')
@@ -53,7 +53,7 @@ def test_mocking_lm1b(self):
5353
self.assertEqual(ex['text'].dtype, tf.int64)
5454
ex['text'].shape.assert_is_compatible_with((None,))
5555

56-
def test_custom_as_dataset(self):
56+
def test_custom_as_dataset(self): # pylint: disable = missing-function-docstring
5757
def _as_dataset(self, *args, **kwargs): # pylint: disable=unused-argument
5858
return tf.data.Dataset.from_generator(
5959
lambda: ({ # pylint: disable=g-long-lambda

tensorflow_datasets/testing/test_case.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ class TestCase(tf.test.TestCase):
4848
"""
4949

5050
@classmethod
51-
def setUpClass(cls):
51+
def setUpClass(cls): # pylint: disable = invalid-name
5252
super(TestCase, cls).setUpClass()
5353
cls.test_data = os.path.join(os.path.dirname(__file__), "test_data")
5454
# Test must not communicate with GCS.
@@ -65,12 +65,12 @@ def gcs_access(self):
6565
gcs_utils.gcs_dataset_info_files = GCS_ACCESS_FNS["dummy_info"]
6666
gcs_utils.is_dataset_on_gcs = GCS_ACCESS_FNS["dummy_datasets"]
6767

68-
def setUp(self):
68+
def setUp(self): # pylint: disable = invalid-name
6969
super(TestCase, self).setUp()
7070
# get_temp_dir is actually the same for all tests, so create a temp sub-dir.
7171
self.tmp_dir = tempfile.mkdtemp(dir=tf.compat.v1.test.get_temp_dir())
7272

73-
def assertRaisesWithPredicateMatch(self, err_type, predicate):
73+
def assertRaisesWithPredicateMatch(self, err_type, predicate): # pylint: disable = invalid-name
7474
if isinstance(predicate, six.string_types):
7575
predicate_fct = lambda err: predicate in str(err)
7676
else:
@@ -79,7 +79,8 @@ def assertRaisesWithPredicateMatch(self, err_type, predicate):
7979
err_type, predicate_fct)
8080

8181
@contextlib.contextmanager
82-
def assertLogs(self, text, level="info"):
82+
def assertLogs(self, text, level="info"): # pylint: disable = invalid-name
83+
"""Log text messages with their level information"""
8384
with absltest.mock.patch.object(logging, level) as mock_log:
8485
yield
8586
concat_logs = ""

tensorflow_datasets/testing/test_utils.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def fake_examples_dir():
7373
return os.path.join(os.path.dirname(__file__), "test_data", "fake_examples")
7474

7575

76-
class FeatureExpectationItem(object):
76+
class FeatureExpectationItem():
7777
"""Test item of a FeatureExpectation."""
7878

7979
def __init__(
@@ -111,7 +111,7 @@ def setUpClass(cls):
111111
cls._sub_test_stack = []
112112

113113
@contextlib.contextmanager
114-
def _subTest(self, test_str):
114+
def _subTest(self, test_str): # pylint: disable = invalid-name, missing-function-docstring
115115
sub_test_not_implemented = True
116116
if sub_test_not_implemented:
117117
yield
@@ -122,7 +122,7 @@ def _subTest(self, test_str):
122122
yield
123123
self._sub_test_stack.pop()
124124

125-
def assertAllEqualNested(self, d1, d2):
125+
def assertAllEqualNested(self, d1, d2): # pylint: disable = invalid-name
126126
"""Same as assertAllEqual but compatible with nested dict."""
127127
if isinstance(d1, dict):
128128
# assertAllEqual do not works well with dictionaries so assert
@@ -213,7 +213,7 @@ def decorated(self, *args, **kwargs):
213213
return decorator
214214

215215

216-
class RaggedConstant(object):
216+
class RaggedConstant():
217217
"""Container of tf.ragged.constant values.
218218
219219
This simple wrapper forward the arguments to delay the RaggedTensor
@@ -233,7 +233,7 @@ class FeatureExpectationsTestCase(SubTestCase):
233233
"""Tests FeatureExpectations with full encode-decode."""
234234

235235
@run_in_graph_and_eager_modes()
236-
def assertFeature(self, feature, shape, dtype, tests, serialized_info=None):
236+
def assertFeature(self, feature, shape, dtype, tests, serialized_info=None): # pylint: disable = invalid-name
237237
"""Test the given feature against the predicates."""
238238

239239
# Check the shape/dtype
@@ -264,7 +264,7 @@ def assertFeature(self, feature, shape, dtype, tests, serialized_info=None):
264264
dtype=dtype,
265265
)
266266

267-
def assertFeatureTest(self, fdict, test, feature, shape, dtype):
267+
def assertFeatureTest(self, fdict, test, feature, shape, dtype): # pylint: disable = invalid-name
268268
"""Test that encode=>decoding of a value works correctly."""
269269
# test feature.encode_example can be pickled and unpickled for beam.
270270
dill.loads(dill.dumps(feature.encode_example))
@@ -385,7 +385,7 @@ def _split_generators(self, dl_manager):
385385
gen_kwargs={"range_": range(20, 30)}),
386386
]
387387

388-
def _generate_examples(self, range_):
388+
def _generate_examples(self, range_): # pylint: disable = arguments-differ
389389
for i in range_:
390390
yield i, {"x": i}
391391

@@ -415,7 +415,7 @@ def _split_generators(self, dl_manager):
415415
gen_kwargs=dict()),
416416
]
417417

418-
def _generate_examples(self):
418+
def _generate_examples(self): # pylint: disable = arguments-differ
419419
for i in range(20):
420420
yield i, {
421421
"image": np.ones((28, 28, 1), dtype=np.uint8),
@@ -479,9 +479,8 @@ def make_mock_check_output(filenames, err_msg):
479479
def check_output(command_args):
480480
if command_args[2] == "files":
481481
return files_call(command_args)
482-
else:
483-
assert command_args[2] == "download"
484-
return dl_call(command_args)
482+
assert command_args[2] == "download"
483+
return dl_call(command_args)
485484

486485
return check_output
487486

@@ -490,7 +489,7 @@ def check_output(command_args):
490489
yield
491490

492491

493-
class DummySerializer(object):
492+
class DummySerializer():
494493
"""To mock example_serializer.ExampleSerializer."""
495494

496495
def __init__(self, specs):
@@ -500,12 +499,11 @@ def serialize_example(self, example):
500499
return bytes(example)
501500

502501

503-
class DummyParser(object):
502+
class DummyParser():
504503
"""To mock example_parser.ExampleParser."""
505504

506505
def __init__(self, specs):
507506
del specs
508507

509508
def parse_example(self, ex):
510509
return ex
511-

tensorflow_datasets/testing/test_utils_test.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
# limitations under the License.
1515

1616
# Lint as: python3
17+
# pylint: disable = missing-class-docstring, missing-function-docstring
1718
"""Tests for tensorflow_datasets.core.test_utils."""
1819

1920
from __future__ import absolute_import
@@ -57,14 +58,14 @@ def test_run_in_graph_and_eager_modes_setup_in_same_mode(self):
5758

5859
class ExampleTest(test_case.TestCase):
5960

60-
def runTest(self):
61+
def runTest(self): # pylint: disable = invalid-name
6162
pass
6263

63-
def setUp(self):
64+
def setUp(self): # pylint: disable = invalid-name
6465
modes.append("setup_" + mode_name())
6566

6667
@test_utils.run_in_graph_and_eager_modes
67-
def testBody(self):
68+
def testBody(self): # pylint: disable = invalid-name
6869
modes.append("run_" + mode_name())
6970

7071
e = ExampleTest()

0 commit comments

Comments
 (0)