Using 'dt' as alias for datetime imports
Many well-known libraries have a conventions regarding which alias to use. Choosing a different one will not break the code but makes it less readable and harder to maintain for other developers. Unless there is specific reason, it is usually best to use the recommended alias which most people are already familiar with. For datetime this convention is dt. Change-Id: Ifba7b7beafdac8377b98ce952b7d3b9dade01670 Closes-Bug: #1535786
This commit is contained in:
parent
0e3f3267df
commit
e34c6c9a5e
@ -13,7 +13,7 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import datetime
|
||||
import datetime as dt
|
||||
|
||||
from rally.common import db
|
||||
from rally import consts
|
||||
@ -67,11 +67,11 @@ class Deployment(object):
|
||||
})
|
||||
|
||||
def set_started(self):
|
||||
self._update({"started_at": datetime.datetime.now(),
|
||||
self._update({"started_at": dt.datetime.now(),
|
||||
"status": consts.DeployStatus.DEPLOY_STARTED})
|
||||
|
||||
def set_completed(self):
|
||||
self._update({"completed_at": datetime.datetime.now(),
|
||||
self._update({"completed_at": dt.datetime.now(),
|
||||
"status": consts.DeployStatus.DEPLOY_FINISHED})
|
||||
|
||||
def add_resource(self, provider_name, type=None, info=None):
|
||||
|
@ -12,7 +12,7 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import datetime
|
||||
import datetime as dt
|
||||
|
||||
import six
|
||||
|
||||
@ -64,7 +64,7 @@ class CeilometerScenario(scenario.OpenStackScenario):
|
||||
if v:
|
||||
sample.update({k: v})
|
||||
len_meta = len(metadata_list) if metadata_list else 0
|
||||
now = timestamp or datetime.datetime.utcnow()
|
||||
now = timestamp or dt.datetime.utcnow()
|
||||
samples = []
|
||||
for i in six.moves.xrange(count):
|
||||
if i and not (i % batch_size):
|
||||
@ -72,7 +72,7 @@ class CeilometerScenario(scenario.OpenStackScenario):
|
||||
samples = []
|
||||
sample_item = dict(sample)
|
||||
sample_item["timestamp"] = (
|
||||
now - datetime.timedelta(seconds=(interval * i))
|
||||
now - dt.timedelta(seconds=(interval * i))
|
||||
).isoformat()
|
||||
if metadata_list:
|
||||
# NOTE(idegtiarov): Adding more than one template of metadata
|
||||
|
@ -10,7 +10,7 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import datetime
|
||||
import datetime as dt
|
||||
import re
|
||||
|
||||
from jinja2 import utils
|
||||
@ -52,7 +52,7 @@ def generate_report(results):
|
||||
"tests": tests,
|
||||
"total": results["tests"],
|
||||
"time": "{0} ({1} s)".format(
|
||||
datetime.timedelta(seconds=round(
|
||||
dt.timedelta(seconds=round(
|
||||
float(results["time"]))), results["time"]),
|
||||
"success": results["success"],
|
||||
"failures": results["failures"],
|
||||
|
@ -29,6 +29,7 @@ Rally Specific Commandments
|
||||
* [N353] - Ensure that unicode() function is not uset because of absence in py3
|
||||
* [N354] - Ensure that ``:raises: Exception`` is not used
|
||||
* [N355] - Ensure that we use only "new-style" Python classes
|
||||
* [N356] - Ensure using ``dt`` as alias for ``datetime``
|
||||
* [N360-N370] - Reserved for rules related to CLI
|
||||
* [N360] - Ensure that CLI modules do not use ``rally.common.db``
|
||||
* [N361] - Ensure that CLI modules do not use ``rally.common.objects``
|
||||
|
@ -64,6 +64,7 @@ re_raises = re.compile(
|
||||
re_db_import = re.compile(r"^from rally.common import db")
|
||||
re_objects_import = re.compile(r"^from rally.common import objects")
|
||||
re_old_type_class = re.compile(r"^\s*class \w+(\(\))?:")
|
||||
re_datetime_alias = re.compile(r"^(from|import) datetime(?!\s+as\s+dt$)")
|
||||
|
||||
|
||||
def skip_ignored_lines(func):
|
||||
@ -489,6 +490,16 @@ def check_old_type_class(logical_line, physical_line, filename):
|
||||
"``object`` or another new-style class.")
|
||||
|
||||
|
||||
@skip_ignored_lines
|
||||
def check_datetime_alias(logical_line, physical_line, filename):
|
||||
"""Ensure using ``dt`` as alias for ``datetime``
|
||||
|
||||
N356
|
||||
"""
|
||||
if re_datetime_alias.search(logical_line):
|
||||
yield (0, "N356 Please use ``dt`` as alias for ``datetime``.")
|
||||
|
||||
|
||||
@skip_ignored_lines
|
||||
def check_db_imports_in_cli(logical_line, physical_line, filename):
|
||||
"""Ensure that CLI modules do not use ``rally.common.db``
|
||||
@ -534,6 +545,7 @@ def factory(register):
|
||||
register(check_dict_formatting_in_string)
|
||||
register(check_using_unicode)
|
||||
register(check_raises)
|
||||
register(check_datetime_alias)
|
||||
register(check_db_imports_in_cli)
|
||||
register(check_objects_imports_in_cli)
|
||||
register(check_old_type_class)
|
||||
|
@ -14,7 +14,7 @@
|
||||
# under the License.
|
||||
|
||||
import copy
|
||||
import datetime as date
|
||||
import datetime as dt
|
||||
import os.path
|
||||
|
||||
import mock
|
||||
@ -606,8 +606,8 @@ class TaskCommandsTestCase(test.TestCase):
|
||||
return_value="123456789")
|
||||
@mock.patch("rally.cli.commands.task.api.Task.list",
|
||||
return_value=[fakes.FakeTask(uuid="a",
|
||||
created_at=date.datetime.now(),
|
||||
updated_at=date.datetime.now(),
|
||||
created_at=dt.datetime.now(),
|
||||
updated_at=dt.datetime.now(),
|
||||
status="c",
|
||||
tag="d",
|
||||
deployment_name="some_name")])
|
||||
@ -630,8 +630,8 @@ class TaskCommandsTestCase(test.TestCase):
|
||||
return_value="123456789")
|
||||
@mock.patch("rally.cli.commands.task.api.Task.list",
|
||||
return_value=[fakes.FakeTask(uuid="a",
|
||||
created_at=date.datetime.now(),
|
||||
updated_at=date.datetime.now(),
|
||||
created_at=dt.datetime.now(),
|
||||
updated_at=dt.datetime.now(),
|
||||
status="c",
|
||||
tag="d",
|
||||
deployment_name="some_name")])
|
||||
|
@ -13,7 +13,7 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import datetime as date
|
||||
import datetime as dt
|
||||
import os.path
|
||||
import tempfile
|
||||
|
||||
@ -150,8 +150,8 @@ class VerifyCommandsTestCase(test.TestCase):
|
||||
def test_list(self, mock_verification_list, mock_print_list):
|
||||
fields = ["UUID", "Deployment UUID", "Set name", "Tests", "Failures",
|
||||
"Created at", "Duration", "Status"]
|
||||
verifications = [{"created_at": date.datetime.now(),
|
||||
"updated_at": date.datetime.now()}]
|
||||
verifications = [{"created_at": dt.datetime.now(),
|
||||
"updated_at": dt.datetime.now()}]
|
||||
mock_verification_list.return_value = verifications
|
||||
self.verify.list()
|
||||
|
||||
|
@ -177,7 +177,7 @@ class DeploymentTestCase(test.TestCase):
|
||||
self.assertEqual(len(resources), 1)
|
||||
self.assertEqual(resources[0]["id"], self.resource["id"])
|
||||
|
||||
@mock.patch("rally.common.objects.deploy.datetime.datetime")
|
||||
@mock.patch("rally.common.objects.deploy.dt.datetime")
|
||||
@mock.patch("rally.common.objects.deploy.db.deployment_update")
|
||||
def test_update_set_started(self, mock_deployment_update, mock_datetime):
|
||||
mock_datetime.now = mock.Mock(return_value="fake_time")
|
||||
@ -190,7 +190,7 @@ class DeploymentTestCase(test.TestCase):
|
||||
"status": consts.DeployStatus.DEPLOY_STARTED}
|
||||
)
|
||||
|
||||
@mock.patch("rally.common.objects.deploy.datetime.datetime")
|
||||
@mock.patch("rally.common.objects.deploy.dt.datetime")
|
||||
@mock.patch("rally.common.objects.deploy.db.deployment_update")
|
||||
def test_update_set_completed(self, mock_deployment_update, mock_datetime):
|
||||
mock_datetime.now = mock.Mock(return_value="fake_time")
|
||||
|
@ -15,7 +15,7 @@
|
||||
|
||||
"""Tests for db.task layer."""
|
||||
|
||||
import datetime
|
||||
import datetime as dt
|
||||
import json
|
||||
|
||||
import ddt
|
||||
@ -173,7 +173,7 @@ class TaskTestCase(test.TestCase):
|
||||
def test_extend_results(self):
|
||||
self.assertRaises(TypeError, objects.Task.extend_results)
|
||||
|
||||
now = datetime.datetime.now()
|
||||
now = dt.datetime.now()
|
||||
iterations = [
|
||||
{"timestamp": i + 2, "duration": i + 5,
|
||||
"scenario_output": {"errors": "", "data": {}},
|
||||
|
@ -13,7 +13,7 @@
|
||||
# under the License.
|
||||
|
||||
import copy
|
||||
import datetime
|
||||
import datetime as dt
|
||||
|
||||
from dateutil import parser
|
||||
import mock
|
||||
@ -33,7 +33,7 @@ class CeilometerScenarioTestCase(test.ScenarioTestCase):
|
||||
def test__make_samples_no_batch_size(self):
|
||||
self.scenario.generate_random_name = mock.Mock(
|
||||
return_value="fake_resource")
|
||||
test_timestamp = datetime.datetime(2015, 10, 20, 14, 18, 40)
|
||||
test_timestamp = dt.datetime(2015, 10, 20, 14, 18, 40)
|
||||
result = list(self.scenario._make_samples(count=2, interval=60,
|
||||
timestamp=test_timestamp))
|
||||
self.assertEqual(1, len(result))
|
||||
@ -51,7 +51,7 @@ class CeilometerScenarioTestCase(test.ScenarioTestCase):
|
||||
def test__make_samples_batch_size(self):
|
||||
self.scenario.generate_random_name = mock.Mock(
|
||||
return_value="fake_resource")
|
||||
test_timestamp = datetime.datetime(2015, 10, 20, 14, 18, 40)
|
||||
test_timestamp = dt.datetime(2015, 10, 20, 14, 18, 40)
|
||||
result = list(self.scenario._make_samples(count=4, interval=60,
|
||||
batch_size=2,
|
||||
timestamp=test_timestamp))
|
||||
|
@ -13,7 +13,7 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import datetime
|
||||
import datetime as dt
|
||||
|
||||
from jsonschema import exceptions as schema_exceptions
|
||||
import mock
|
||||
@ -192,8 +192,8 @@ class WaitForTestCase(test.TestCase):
|
||||
seconds=self.load_secs)
|
||||
|
||||
def get_fake_checker_delayed(self, **delay):
|
||||
deadline = datetime.datetime.now() + datetime.timedelta(**delay)
|
||||
return lambda obj: datetime.datetime.now() > deadline
|
||||
deadline = dt.datetime.now() + dt.timedelta(**delay)
|
||||
return lambda obj: dt.datetime.now() > deadline
|
||||
|
||||
def fake_checker_false(self, obj):
|
||||
return False
|
||||
|
@ -376,3 +376,17 @@ class HackingTestCase(test.TestCase):
|
||||
checkres = checks.check_old_type_class(line, line, "fakefile")
|
||||
self.assertIsNotNone(next(checkres))
|
||||
self.assertEqual([], list(checkres))
|
||||
|
||||
def test_check_datetime_alias(self):
|
||||
lines = ["import datetime as date",
|
||||
"import datetime",
|
||||
"import datetime as dto",
|
||||
"from datetime import datetime as dtime"]
|
||||
|
||||
for line in lines:
|
||||
checkres = checks.check_datetime_alias(line, line, "fakefile")
|
||||
self.assertIsNotNone(next(checkres))
|
||||
self.assertEqual([], list(checkres))
|
||||
|
||||
line = "import datetime as dt"
|
||||
checkres = checks.check_datetime_alias(line, line, "fakefile")
|
||||
|
@ -10,7 +10,7 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import datetime
|
||||
import datetime as dt
|
||||
|
||||
import mock
|
||||
|
||||
@ -53,7 +53,7 @@ class HtmlOutputTestCase(test.TestCase):
|
||||
"unexpected_success": 0,
|
||||
"total": 4,
|
||||
"time": "{0} ({1} s)".format(
|
||||
datetime.timedelta(seconds=23), 22.75),
|
||||
dt.timedelta(seconds=23), 22.75),
|
||||
"tests": [{"name": "tf",
|
||||
"id": 0,
|
||||
"output": "fail_log",
|
||||
@ -99,7 +99,7 @@ class HtmlOutputTestCase(test.TestCase):
|
||||
"expected_failures": 0,
|
||||
"unexpected_success": 0,
|
||||
"total": 1,
|
||||
"time": "{0} ({1} s)".format(datetime.timedelta(seconds=0), 0),
|
||||
"time": "{0} ({1} s)".format(dt.timedelta(seconds=0), 0),
|
||||
"tests": [{
|
||||
"id": 0,
|
||||
"status": "skip",
|
||||
|
Loading…
Reference in New Issue
Block a user