Passed
Pull Request — master (#15)
by
unknown
02:07
created

LocalizedFileFieldTestCase.test_assign()   F

Complexity

Conditions 10

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 10
c 1
b 0
f 1
dl 0
loc 26
rs 3.1304

How to fix   Complexity   

Complexity

Complex classes like LocalizedFileFieldTestCase.test_assign() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import os
2
import shutil
3
import tempfile as sys_tempfile
4
import pickle
5
6
from django import forms
0 ignored issues
show
Configuration introduced by
The import django could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
7
from django.test import TestCase, override_settings
0 ignored issues
show
Configuration introduced by
The import django.test could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
8
from django.core.files.base import File, ContentFile
0 ignored issues
show
Configuration introduced by
The import django.core.files.base could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
9
from django.core.files import temp as tempfile
0 ignored issues
show
Configuration introduced by
The import django.core.files could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
10
from localized_fields import LocalizedFileField, LocalizedValue
11
from localized_fields.fields.localized_file_field import LocalizedFieldFile
12
from localized_fields.forms import LocalizedFileFieldForm
13
from localized_fields.localized_value import LocalizedFileValue
14
from localized_fields.widgets import LocalizedFileWidget
15
from .fake_model import get_fake_model
16
17
18
MEDIA_ROOT = sys_tempfile.mkdtemp()
19
20
21
@override_settings(MEDIA_ROOT=MEDIA_ROOT)
0 ignored issues
show
Coding Style introduced by
This class has no __init__ method.
Loading history...
22
class LocalizedFileFieldTestCase(TestCase):
23
    """Tests the localized slug classes."""
24
25
    @classmethod
26
    def setUpClass(cls):
27
        """Creates the test models in the database."""
28
29
        super().setUpClass()
30
31
        cls.FileFieldModel = get_fake_model(
32
            'LocalizedFileFieldTestModel',
33
            {
34
                'file': LocalizedFileField(),
35
            }
36
        )
37
        if not os.path.isdir(MEDIA_ROOT):
38
            os.makedirs(MEDIA_ROOT)
39
40
    @classmethod
41
    def tearDownClass(cls):
42
        super().tearDownClass()
43
        shutil.rmtree(MEDIA_ROOT)
44
45
    @classmethod
46
    def test_assign(cls):
47
        """Tests whether the :see:LocalizedFileValueDescriptor works properly"""
48
49
        temp_file = tempfile.NamedTemporaryFile(dir=MEDIA_ROOT)
50
        instance = cls.FileFieldModel()
51
        instance.file = {'en': temp_file.name}
52
        assert isinstance(instance.file.en, LocalizedFieldFile)
53
        assert instance.file.en.name == temp_file.name
54
55
        field_dump = pickle.dumps(instance.file)
56
        instance = cls.FileFieldModel()
57
        instance.file = pickle.loads(field_dump)
58
        assert instance.file.en.field == instance._meta.get_field('file')
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _meta was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
59
        assert instance.file.en.instance == instance
60
        assert isinstance(instance.file.en, LocalizedFieldFile)
61
62
        instance = cls.FileFieldModel()
63
        instance.file = {'en': ContentFile("test", "testfilename")}
64
        assert isinstance(instance.file.en, LocalizedFieldFile)
65
        assert instance.file.en.name == "testfilename"
66
67
        another_instance = cls.FileFieldModel()
68
        another_instance.file = {'ro': instance.file.en}
69
        assert another_instance == another_instance.file.ro.instance
70
        assert another_instance.file.ro.lang == 'ro'
71
72
    @classmethod
73
    def test_save_form_data(cls):
74
        """Tests whether the :see:save_form_data function correctly set 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
75
        a valid value."""
76
77
        instance = cls.FileFieldModel()
78
        data = LocalizedFileValue({'en': False})
79
        instance._meta.get_field('file').save_form_data(instance, data)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _meta was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
80
        assert instance.file.en == ''
81
82
    @classmethod
83
    def test_pre_save(cls):
84
        """Tests whether the :see:pre_save function works properly."""
85
86
        instance = cls.FileFieldModel()
87
        instance.file = {'en': ContentFile("test", "testfilename")}
88
        instance._meta.get_field('file').pre_save(instance, False)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _meta was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
89
        assert instance.file.en._committed == True
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _committed was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
90
91
    @classmethod
92
    def test_file_methods(cls):
93
        """Tests whether the :see:LocalizedFieldFile.delete method works
94
        correctly."""
95
96
        temp_file = File(tempfile.NamedTemporaryFile())
97
        instance = cls.FileFieldModel()
98
        # Calling delete on an unset FileField should not call the file deletion
99
        # process, but fail silently
100
        instance.file.en.delete()
101
        instance.file.en.save('testfilename', temp_file)
102
        assert instance.file.en.name == 'testfilename'
103
        instance.file.en.delete()
104
        assert instance.file.en.name is None
105
106
    @classmethod
107
    def test_generate_filename(cls):
108
        """Tests whether the :see:LocalizedFieldFile.generate_filename method
109
        works correctly."""
110
111
        instance = cls.FileFieldModel()
112
        field = instance._meta.get_field('file')
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _meta was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
113
        field.upload_to = '{lang}/'
114
        filename = field.generate_filename(instance, 'test', 'en')
115
        assert filename == 'en/test'
116
        field.upload_to = lambda instance, filename, lang: \
117
            '%s_%s' % (lang, filename)
118
        filename = field.generate_filename(instance, 'test', 'en')
119
        assert filename == 'en_test'
120
121
    @staticmethod
122
    def test_get_prep_value():
123
        """Tests whether the :see:get_prep_value function returns correctly 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
124
        value."""
125
126
        value = LocalizedValue({'en': None})
127
        assert LocalizedFileField().get_prep_value(None) == None
128
        assert isinstance(LocalizedFileField().get_prep_value(value), dict)
129
        assert LocalizedFileField().get_prep_value(value)['en'] == ''
130
131
    @staticmethod
132
    def test_formfield():
133
        """Tests whether the :see:formfield function correctly returns 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
134
        a valid form."""
135
136
        form_field = LocalizedFileField().formfield()
137
        assert isinstance(form_field, LocalizedFileFieldForm)
138
        assert isinstance(form_field, forms.FileField)
139
        assert isinstance(form_field.widget, LocalizedFileWidget)
140
141
    @staticmethod
142
    def test_deconstruct():
143
        """Tests whether the :see:LocalizedFileField
144
        class's :see:deconstruct function works properly."""
145
146
        name, path, args, kwargs = LocalizedFileField().deconstruct()
0 ignored issues
show
Unused Code introduced by
The variable name seems to be unused.
Loading history...
Unused Code introduced by
The variable args seems to be unused.
Loading history...
Unused Code introduced by
The variable path seems to be unused.
Loading history...
147
        assert 'upload_to' in kwargs
148
        assert 'storage' not in kwargs
149
        name, path, \
150
        args, kwargs = LocalizedFileField(storage='test').deconstruct()
151
        assert 'storage' in kwargs
152