Passed
Push — master ( f7c14f...06873a )
by Swen
02:26
created

LocalizedFileFieldTestCase   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 131
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 36
c 2
b 0
f 1
dl 0
loc 131
rs 8.8

10 Methods

Rating   Name   Duplication   Size   Complexity  
A test_get_prep_value() 0 9 4
A test_generate_filename() 0 14 4
A test_file_methods() 0 14 3
A test_save_form_data() 0 9 2
F test_assign() 0 26 10
A tearDownClass() 0 4 1
A test_formfield() 0 9 4
A setUpClass() 0 14 2
A test_deconstruct() 0 11 4
A test_pre_save() 0 8 2
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.fields import LocalizedFileField
11
from localized_fields.value import LocalizedValue
12
from localized_fields.fields.file_field import LocalizedFieldFile
13
from localized_fields.forms import LocalizedFileFieldForm
14
from localized_fields.value import LocalizedFileValue
15
from localized_fields.widgets import LocalizedFileWidget
16
from .fake_model import get_fake_model
17
18
19
MEDIA_ROOT = sys_tempfile.mkdtemp()
20
21
22
@override_settings(MEDIA_ROOT=MEDIA_ROOT)
0 ignored issues
show
Coding Style introduced by
This class has no __init__ method.
Loading history...
23
class LocalizedFileFieldTestCase(TestCase):
24
    """Tests the localized slug classes."""
25
26
    @classmethod
27
    def setUpClass(cls):
28
        """Creates the test models in the database."""
29
30
        super().setUpClass()
31
32
        cls.FileFieldModel = get_fake_model(
33
            'LocalizedFileFieldTestModel',
34
            {
35
                'file': LocalizedFileField(),
36
            }
37
        )
38
        if not os.path.isdir(MEDIA_ROOT):
39
            os.makedirs(MEDIA_ROOT)
40
41
    @classmethod
42
    def tearDownClass(cls):
43
        super().tearDownClass()
44
        shutil.rmtree(MEDIA_ROOT)
45
46
    @classmethod
47
    def test_assign(cls):
48
        """Tests whether the :see:LocalizedFileValueDescriptor works properly"""
49
50
        temp_file = tempfile.NamedTemporaryFile(dir=MEDIA_ROOT)
51
        instance = cls.FileFieldModel()
52
        instance.file = {'en': temp_file.name}
53
        assert isinstance(instance.file.en, LocalizedFieldFile)
54
        assert instance.file.en.name == temp_file.name
55
56
        field_dump = pickle.dumps(instance.file)
57
        instance = cls.FileFieldModel()
58
        instance.file = pickle.loads(field_dump)
59
        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...
60
        assert instance.file.en.instance == instance
61
        assert isinstance(instance.file.en, LocalizedFieldFile)
62
63
        instance = cls.FileFieldModel()
64
        instance.file = {'en': ContentFile("test", "testfilename")}
65
        assert isinstance(instance.file.en, LocalizedFieldFile)
66
        assert instance.file.en.name == "testfilename"
67
68
        another_instance = cls.FileFieldModel()
69
        another_instance.file = {'ro': instance.file.en}
70
        assert another_instance == another_instance.file.ro.instance
71
        assert another_instance.file.ro.lang == 'ro'
72
73
    @classmethod
74
    def test_save_form_data(cls):
75
        """Tests whether the :see:save_form_data function correctly set 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
76
        a valid value."""
77
78
        instance = cls.FileFieldModel()
79
        data = LocalizedFileValue({'en': False})
80
        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...
81
        assert instance.file.en == ''
82
83
    @classmethod
84
    def test_pre_save(cls):
85
        """Tests whether the :see:pre_save function works properly."""
86
87
        instance = cls.FileFieldModel()
88
        instance.file = {'en': ContentFile("test", "testfilename")}
89
        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...
90
        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...
91
92
    @classmethod
93
    def test_file_methods(cls):
94
        """Tests whether the :see:LocalizedFieldFile.delete method works
95
        correctly."""
96
97
        temp_file = File(tempfile.NamedTemporaryFile())
98
        instance = cls.FileFieldModel()
99
        # Calling delete on an unset FileField should not call the file deletion
100
        # process, but fail silently
101
        instance.file.en.delete()
102
        instance.file.en.save('testfilename', temp_file)
103
        assert instance.file.en.name == 'testfilename'
104
        instance.file.en.delete()
105
        assert instance.file.en.name is None
106
107
    @classmethod
108
    def test_generate_filename(cls):
109
        """Tests whether the :see:LocalizedFieldFile.generate_filename method
110
        works correctly."""
111
112
        instance = cls.FileFieldModel()
113
        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...
114
        field.upload_to = '{lang}/'
115
        filename = field.generate_filename(instance, 'test', 'en')
116
        assert filename == 'en/test'
117
        field.upload_to = lambda instance, filename, lang: \
118
            '%s_%s' % (lang, filename)
119
        filename = field.generate_filename(instance, 'test', 'en')
120
        assert filename == 'en_test'
121
122
    @staticmethod
123
    def test_get_prep_value():
124
        """Tests whether the :see:get_prep_value function returns correctly 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
125
        value."""
126
127
        value = LocalizedValue({'en': None})
128
        assert LocalizedFileField().get_prep_value(None) == None
129
        assert isinstance(LocalizedFileField().get_prep_value(value), dict)
130
        assert LocalizedFileField().get_prep_value(value)['en'] == ''
131
132
    @staticmethod
133
    def test_formfield():
134
        """Tests whether the :see:formfield function correctly returns 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
135
        a valid form."""
136
137
        form_field = LocalizedFileField().formfield()
138
        assert isinstance(form_field, LocalizedFileFieldForm)
139
        assert isinstance(form_field, forms.FileField)
140
        assert isinstance(form_field.widget, LocalizedFileWidget)
141
142
    @staticmethod
143
    def test_deconstruct():
144
        """Tests whether the :see:LocalizedFileField
145
        class's :see:deconstruct function works properly."""
146
147
        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 path seems to be unused.
Loading history...
Unused Code introduced by
The variable args seems to be unused.
Loading history...
148
        assert 'upload_to' in kwargs
149
        assert 'storage' not in kwargs
150
        name, path, \
151
        args, kwargs = LocalizedFileField(storage='test').deconstruct()
152
        assert 'storage' in kwargs
153