Skip to content

Commit

Permalink
Remove custom DurationField, replace with IntegerField
Browse files Browse the repository at this point in the history
the custom field derives from models.IntegerField so replace with
that. Next we're going to make use of Django's own
models.DurationField.
  • Loading branch information
atodorov committed Mar 14, 2018
1 parent 97bca43 commit 2667ab4
Show file tree
Hide file tree
Showing 11 changed files with 16 additions and 115 deletions.
27 changes: 0 additions & 27 deletions tcms/core/forms/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@
from django.db.models import Q
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

from tcms.core.utils import string_to_list
from tcms.core.utils.timedelta2int import timedelta2int


class UserField(forms.CharField):
Expand Down Expand Up @@ -46,31 +44,6 @@ def clean(self, value):
raise ValidationError('Unknown user: "%s"' % value)


class DurationField(forms.CharField):
"""
Customizing forms CharFiled validation.
estimated_time using integer mix with d(ay), h(our), m(inute)
"""
default_error_messages = {
'invalid': _(u'Enter a valid estimated time. e.g. 12h45m'),
}

def __init__(self, *args, **kwargs):
super(DurationField, self).__init__(*args, **kwargs)

def validate(self, value):
super(DurationField, self).validate(value)
try:
from tcms.xmlrpc.utils import pre_process_estimated_time
pre_process_estimated_time(value)
except ValueError:
raise forms.ValidationError(self.error_messages['invalid'])

def clean(self, value):
value = super(DurationField, self).clean(value)
return timedelta2int(value)


class MultipleEmailField(forms.EmailField):
def clean(self, value):
"""
Expand Down
37 changes: 0 additions & 37 deletions tcms/core/models/fields.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,8 @@
# -*- coding: utf-8 -*-
import datetime

try:
# may not be running under MySQL
from MySQLdb.constants import FIELD_TYPE
from django.db.backends.mysql.base import django_conversions
django_conversions.update({FIELD_TYPE.TIME: None})
except ImportError:
pass

from django.db.models.fields import IntegerField

from tcms.core.forms.fields import DurationField as DurationFormField


class DurationField(IntegerField):
def from_db_value(self, value, expression, connection):
return self.to_python(value)

def to_python(self, value):
if isinstance(value, int):
return datetime.timedelta(seconds=value)
elif isinstance(value, datetime.timedelta):
return value
else:
raise TypeError('Unable to convert %s to timedelta.' % value)

def get_db_prep_value(self, value, connection, prepared):
"""convert datetime.timedelta to seconds.
1 day equal to 86400 seconds
"""
if isinstance(value, datetime.timedelta):
return value.seconds + (86400 * value.days)
else:
value = super(DurationField, self).get_db_prep_value(value,
connection,
prepared)
return value

def formfield(self, form_class=DurationFormField, **kwargs):
defaults = {'help_text': 'Enter duration in the format: DDHHMM'}
defaults.update(kwargs)
return form_class(**defaults)
25 changes: 0 additions & 25 deletions tcms/core/utils/timedelta2int.py

This file was deleted.

6 changes: 3 additions & 3 deletions tcms/testcases/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from tinymce.widgets import TinyMCE

from tcms.core.forms.fields import UserField, DurationField, StripURLField
from tcms.core.forms.fields import UserField, StripURLField
from tcms.core.utils import string_to_list
from tcms.core.utils.validations import validate_bug_id
from tcms.testplans.models import TestPlan
Expand Down Expand Up @@ -105,7 +105,7 @@ class BaseCaseForm(forms.Form):
widget=forms.Textarea,
required=False
)
estimated_time = DurationField(label='Estimated Time', initial='0m', required=False)
estimated_time = forms.DurationField(label='Estimated Time', initial='0', required=False)
setup = forms.CharField(label="Setup", widget=TinyMCE(), required=False)
action = forms.CharField(label="Actions", widget=TinyMCE(), required=False)
effect = forms.CharField(label="Expect results", widget=TinyMCE(), required=False)
Expand Down Expand Up @@ -219,7 +219,7 @@ class CaseNotifyForm(forms.Form):


class XMLRPCBaseCaseForm(BaseCaseForm):
estimated_time = DurationField(required=False)
estimated_time = forms.DurationField(required=False)
is_automated = forms.ChoiceField(
choices=FULL_AUTOMATED_CHOICES,
widget=forms.CheckboxSelectMultiple(),
Expand Down
3 changes: 1 addition & 2 deletions tcms/testcases/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from django.db import migrations, models

import tcms.core.models.base
import tcms.core.models.fields


class Migration(migrations.Migration):
Expand Down Expand Up @@ -46,7 +45,7 @@ class Migration(migrations.Migration):
('requirement', models.CharField(max_length=255, blank=True)),
('alias', models.CharField(max_length=255, blank=True)),
('estimated_time',
tcms.core.models.fields.DurationField(default=0, db_column='estimated_time')),
models.IntegerField(default=0, db_column='estimated_time')),
('notes', models.TextField(blank=True)),
],
options={
Expand Down
3 changes: 1 addition & 2 deletions tcms/testcases/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

from tcms.core.models import TCMSActionModel
from tcms.core.models.base import TCMSContentTypeBaseModel
from tcms.core.models.fields import DurationField
from tcms.core.utils.checksum import checksum
from tcms.core.utils.timedeltaformat import format_timedelta
from tcms.issuetracker.types import IssueTrackerType
Expand Down Expand Up @@ -128,7 +127,7 @@ class TestCase(TCMSActionModel):
summary = models.CharField(max_length=255)
requirement = models.CharField(max_length=255, blank=True, null=True)
alias = models.CharField(max_length=255, blank=True)
estimated_time = DurationField(db_column='estimated_time', default=0)
estimated_time = models.IntegerField(db_column='estimated_time', default=0) # DurationField
notes = models.TextField(blank=True, null=True)

case_status = models.ForeignKey(TestCaseStatus, on_delete=models.CASCADE)
Expand Down
4 changes: 2 additions & 2 deletions tcms/testruns/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from django.contrib.auth.models import User

from tcms.core.utils import string_to_list
from tcms.core.forms.fields import UserField, DurationField
from tcms.core.forms.fields import UserField
from tcms.management.models import Product, Version, Build, EnvGroup
from tcms.testplans.models import TestPlan
from tcms.testcases.models import TestCase
Expand Down Expand Up @@ -42,7 +42,7 @@ class BaseRunForm(forms.Form):
queryset=Product.objects.all(),
empty_label=None,
)
estimated_time = DurationField(required=False)
estimated_time = forms.DurationField(required=False)
product_version = forms.ModelChoiceField(
label='Product Version',
queryset=Version.objects.none(),
Expand Down
3 changes: 1 addition & 2 deletions tcms/testruns/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from django.db import migrations, models
import tcms.core.models.base
from django.conf import settings
import tcms.core.models.fields


class Migration(migrations.Migration):
Expand Down Expand Up @@ -72,7 +71,7 @@ class Migration(migrations.Migration):
('stop_date', models.DateTimeField(db_index=True, null=True, blank=True)),
('summary', models.TextField()),
('notes', models.TextField(blank=True)),
('estimated_time', tcms.core.models.fields.DurationField(default=0, max_length=11)),
('estimated_time', models.IntegerField(default=0)),
('environment_id', models.IntegerField(default=0)),
('auto_update_run_status', models.BooleanField(default=False)),
('build', models.ForeignKey(related_name='build_run', to='management.TestBuild',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
# -*- coding: utf-8 -*-
from django.db import migrations
import tcms.core.models.fields


class Migration(migrations.Migration):

"""
As part of migrating to Django's own DurationField
we don't need this anymore.
"""
dependencies = [
('testruns', '0002_add_initial_data'),
]

operations = [
migrations.AlterField(
model_name='testrun',
name='estimated_time',
field=tcms.core.models.fields.DurationField(default=0),
),
]
# deliberately left empty
operations = []
3 changes: 1 addition & 2 deletions tcms/testruns/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import vinaigrette

from tcms.core.contrib.linkreference.models import LinkReference
from tcms.core.models.fields import DurationField
from tcms.core.models import TCMSActionModel
from tcms.core.utils import is_int
from tcms.core.utils.timedeltaformat import format_timedelta
Expand All @@ -36,7 +35,7 @@ class TestRun(TCMSActionModel):
stop_date = models.DateTimeField(null=True, blank=True, db_index=True)
summary = models.TextField()
notes = models.TextField(blank=True)
estimated_time = DurationField(default=0)
estimated_time = models.IntegerField(default=0) # todo: DurationField

plan = models.ForeignKey('testplans.TestPlan', related_name='run',
on_delete=models.CASCADE)
Expand Down
5 changes: 1 addition & 4 deletions tcms/xmlrpc/api/testcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from modernrpc.core import rpc_method, REQUEST_KEY

from tcms.core.utils import string_to_list, form_errors_to_list
from tcms.core.utils.timedelta2int import timedelta2int
from tcms.management.models import Tag
from tcms.management.models import Component
from tcms.testcases.models import TestCase
Expand Down Expand Up @@ -315,9 +314,7 @@ def filter(query):
:rtype: list(dict)
"""
if query.get('estimated_time'):
query['estimated_time'] = timedelta2int(
pre_process_estimated_time(query.get('estimated_time'))
)
query['estimated_time'] = pre_process_estimated_time(query.get('estimated_time'))

results = []
for case in TestCase.objects.filter(**query):
Expand Down

0 comments on commit 2667ab4

Please sign in to comment.