Passed
Pull Request — master (#69)
by Gleyberson
02:03
created

build.setup.TestCommand.initialize_options()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
"""Setup script.
2
3
Run "python3 setup.py --help-commands" to list all available commands and their
4
descriptions.
5
"""
6
import json
7
import os
8
import shutil
9
import sys
10
from abc import abstractmethod
11
from pathlib import Path
12
from subprocess import CalledProcessError, call, check_call
13
14
from setuptools import Command, setup
15
from setuptools.command.develop import develop
16
# from setuptools.command.egg_info import egg_info
17
from setuptools.command.install import install
18
19
if 'bdist_wheel' in sys.argv:
20
    raise RuntimeError("This setup.py does not support wheels")
21
22
# Paths setup with virtualenv detection
23
BASE_ENV = Path(os.environ.get('VIRTUAL_ENV', '/'))
24
# Kytos var folder
25
VAR_PATH = BASE_ENV / 'var' / 'lib' / 'kytos'
26
# Path for enabled NApps
27
ENABLED_PATH = VAR_PATH / 'napps'
28
# Path to install NApps
29
INSTALLED_PATH = VAR_PATH / 'napps' / '.installed'
30
CURRENT_DIR = Path('.').resolve()
31
32
# NApps enabled by default
33
# CORE_NAPPS = ['of_core']
34
35
36
class SimpleCommand(Command):
37
    """Make Command implementation simpler."""
38
39
    user_options = []
40
41
    @abstractmethod
42
    def run(self):
43
        """Run when command is invoked.
44
45
        Use *call* instead of *check_call* to ignore failures.
46
        """
47
    def initialize_options(self):
48
        """Set default values for options."""
49
50
    def finalize_options(self):
51
        """Post-process options."""
52
53
54
# pylint: disable=attribute-defined-outside-init, abstract-method
55
class TestCommand(SimpleCommand):
56
    """Test tags decorators."""
57
58
    user_options = [
59
        ('size=', None, 'Specify the size of tests to be executed.'),
60
        ('type=', None, 'Specify the type of tests to be executed.'),
61
    ]
62
63
    sizes = ('small', 'medium', 'large', 'all')
64
    types = ('unit', 'integration', 'e2e')
65
66
    def initialize_options(self):
67
        """Set default size and type decorator tests."""
68
        self.size = 'all'
69
        self.type = 'unit'
70
71
    def finalize_options(self):
72
        """Post-process."""
73
        try:
74
            assert self.size in self.sizes, ('ERROR: Invalid size:'
75
                                             f':{self.size}')
76
            assert self.type in self.types, ('ERROR: Invalid type:'
77
                                             f':{self.type}')
78
        except AssertionError as exc:
79
            print(exc)
80
            sys.exit(-1)
81
82
83
class Cleaner(SimpleCommand):
84
    """Custom clean command to tidy up the project root."""
85
86
    description = 'clean build, dist, pyc and egg from package and docs'
87
88
    def run(self):
89
        """Clean build, dist, pyc and egg from package and docs."""
90
        call('rm -vrf ./build ./dist ./*.egg-info', shell=True)
91
        call('find . -name __pycache__ -type d | xargs rm -rf', shell=True)
92
        call('make -C docs/ clean', shell=True)
93
94
95
class Test(TestCommand):
96
    """Run all tests."""
97
98
    description = 'run tests and display results'
99
100
    def run(self):
101
        """Run tests."""
102
        markers = self.size
103
        if markers == "small":
104
            sizes = list(self.sizes)
105
            sizes.remove(self.size)
106
            markers = "".join(['not %s and ' % size for size in sizes])[:-5]
107
108
        size_args = "" if self.size == "all" else "-m '%s'" % markers
109
        args = '--addopts="tests/%s %s"' % (self.type, size_args)
110
        cmd = 'python3.6 setup.py test_fw %s' % args
111
        try:
112
            check_call(cmd, shell=True)
113
        except CalledProcessError as exc:
114
            print(exc)
115
116
117
class TestCoverage(TestCommand):
118
    """Display test coverage."""
119
120
    description = 'run tests and display code coverage'
121
122
    def run(self):
123
        """Run tests quietly and display coverage report."""
124
        args = '--size %s --type %s' % (self.size, self.type)
125
        cmd = 'coverage3 run setup.py test %s && coverage3 report' % args
126
        check_call(cmd, shell=True)
127
128
129
class CITest(TestCommand):
130
    """Run all CI tests."""
131
132
    description = 'run all CI tests: unit and doc tests, linter'
133
134
    def run(self):
135
        """Run unit tests with coverage, doc tests and linter."""
136
        args = '--size %s --type %s' % (self.size, self.type)
137
        coverage_cmd = 'python3.6 setup.py coverage %s' % args
138
        lint_cmd = 'python3.6 setup.py lint'
139
        cmd = '%s && %s' % (coverage_cmd, lint_cmd)
140
        check_call(cmd, shell=True)
141
142
143
class Linter(SimpleCommand):
144
    """Code linters."""
145
146
    description = 'lint Python source code'
147
148
    def run(self):
149
        """Run yala."""
150
        print('Yala is running. It may take several seconds...')
151
        check_call('yala *.py v0x?? tests', shell=True)
152
153
154
# class KytosInstall:
155
#     """Common code for all install types."""
156
#
157
#     @staticmethod
158
#     def enable_core_napps():
159
#         """Enable a NAPP by creating a symlink."""
160
#         (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
161
#         for napp in CORE_NAPPS:
162
#             napp_path = Path('kytos', napp)
163
#             src = ENABLED_PATH / napp_path
164
#             dst = INSTALLED_PATH / napp_path
165
#             src.symlink_to(dst)
166
167
168
class InstallMode(install):
169
    """Create files in var/lib/kytos."""
170
171
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
172
173
    def run(self):
174
        """Create of_core as default napps enabled."""
175
        print(self.description)
176
177
178
# class EggInfo(egg_info):
179
#     """Prepare files to be packed."""
180
#
181
#     def run(self):
182
#         """Build css."""
183
#         self._install_deps_wheels()
184
#         super().run()
185
#
186
#     @staticmethod
187
#     def _install_deps_wheels():
188
#         """Python wheels are much faster (no compiling)."""
189
#         print('Installing dependencies...')
190
#         check_call([sys.executable, '-m', 'pip', 'install', '-r',
191
#                     'requirements/run.in'])
192
193
194
class DevelopMode(develop):
195
    """Recommended setup for kytos-napps developers.
196
197
    Instead of copying the files to the expected directories, a symlink is
198
    created on the system aiming the current source code.
199
    """
200
201
    description = 'install NApps in development mode'
202
203
    def run(self):
204
        """Install the package in a developer mode."""
205
        super().run()
206
        if self.uninstall:
207
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
208
        else:
209
            self._create_folder_symlinks()
210
            # self._create_file_symlinks()
211
            # KytosInstall.enable_core_napps()
212
213
    @staticmethod
214
    def _create_folder_symlinks():
215
        """Symlink to all Kytos NApps folders.
216
217
        ./napps/kytos/napp_name will generate a link in
218
        var/lib/kytos/napps/.installed/kytos/napp_name.
219
        """
220
        links = INSTALLED_PATH / 'kytos'
221
        links.mkdir(parents=True, exist_ok=True)
222
        code = CURRENT_DIR
223
        src = links / 'of_core'
224
        symlink_if_different(src, code)
225
226
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
227
        dst = ENABLED_PATH / Path('kytos', 'of_core')
228
        symlink_if_different(dst, src)
229
230
    # @staticmethod
231
    # def _create_file_symlinks():
232
    #     """Symlink to required files."""
233
    #     src = ENABLED_PATH / '__init__.py'
234
    #     dst = CURRENT_DIR / 'napps' / '__init__.py'
235
    #     symlink_if_different(src, dst)
236
237
238
def symlink_if_different(path, target):
239
    """Force symlink creation if it points anywhere else."""
240
    # print(f"symlinking {path} to target: {target}...", end=" ")
241
    if not path.exists():
242
        # print(f"path doesn't exist. linking...")
243
        path.symlink_to(target)
244
    elif not path.samefile(target):
245
        # print(f"path exists, but is different. removing and linking...")
246
        # Exists but points to a different file, so let's replace it
247
        path.unlink()
248
        path.symlink_to(target)
249
250
251
def read_version_from_json():
252
    """Read the NApp version from NApp kytos.json file."""
253
    file = Path('kytos.json')
254
    metadata = json.loads(file.read_text())
255
    return metadata['version']
256
257
258
setup(name='kytos_of_core',
259
      version=read_version_from_json(),
260
      description='Core NApps developed by Kytos Team',
261
      url='http://github.com/kytos/of_core',
262
      author='Kytos Team',
263
      author_email='[email protected]',
264
      license='MIT',
265
      setup_requires=['pytest-runner'],
266
      tests_require=['pytest'],
267
      extras_require={
268
          'dev': [
269
              'coverage',
270
              'pip-tools',
271
              'yala',
272
              'tox',
273
          ],
274
      },
275
      cmdclass={
276
          'clean': Cleaner,
277
          'ci': CITest,
278
          'coverage': TestCoverage,
279
          'develop': DevelopMode,
280
          'install': InstallMode,
281
          'lint': Linter,
282
          'test': Test,
283
          # 'egg_info': EggInfo,
284
      },
285
      zip_safe=False,
286
      classifiers=[
287
          'License :: OSI Approved :: MIT License',
288
          'Operating System :: POSIX :: Linux',
289
          'Programming Language :: Python :: 3.6',
290
          'Topic :: System :: Networking',
291
      ])
292