Completed
Pull Request — master (#69)
by Gleyberson
03:59 queued 01:56
created

build.setup.TestCommand.finalize_options()   A

Complexity

Conditions 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 10
rs 10
c 0
b 0
f 0
cc 2
nop 1
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 TestCoverage(TestCommand):
96
    """Display test coverage."""
97
98
    description = 'run unit tests and display code coverage'
99
100
    def run(self):
101
        """Run unittest quietly and display coverage report."""
102
        sizes = list(self.sizes)
103
        sizes.remove(self.size)
104
105
        markers = self.size
106
        if markers == "small":
107
            markers = "".join(['not %s and ' % size for size in sizes])[:-5]
108
109
        size_args = "" if self.size == "all" else "-m '%s'" % markers
110
        args = '--addopts="tests/%s %s"' % (self.type, size_args)
111
        cmd = 'coverage3 run setup.py test %s && coverage3 report' % args
112
        print(cmd)
113
        try:
114
            check_call(cmd, shell=True)
115
        except CalledProcessError as exc:
116
            print(exc)
117
118
119
class Linter(SimpleCommand):
120
    """Code linters."""
121
122
    description = 'lint Python source code'
123
124
    def run(self):
125
        """Run yala."""
126
        print('Yala is running. It may take several seconds...')
127
        check_call('yala *.py v0x?? tests', shell=True)
128
129
130
class CITest(TestCommand):
131
    """Run all CI tests."""
132
133
    description = 'run all CI tests: unit and doc tests, linter'
134
135
    def run(self):
136
        """Run unit tests with coverage, doc tests and linter."""
137
        args = '--size %s --type %s' % (self.size, self.type)
138
        coverage_cmd = 'python3.6 setup.py coverage %s' % args
139
        lint_cmd = 'python3.6 setup.py lint'
140
        cmd = '%s && %s' % (coverage_cmd, lint_cmd)
141
        check_call(cmd, shell=True)
142
143
144
# class KytosInstall:
145
#     """Common code for all install types."""
146
#
147
#     @staticmethod
148
#     def enable_core_napps():
149
#         """Enable a NAPP by creating a symlink."""
150
#         (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
151
#         for napp in CORE_NAPPS:
152
#             napp_path = Path('kytos', napp)
153
#             src = ENABLED_PATH / napp_path
154
#             dst = INSTALLED_PATH / napp_path
155
#             src.symlink_to(dst)
156
157
158
class InstallMode(install):
159
    """Create files in var/lib/kytos."""
160
161
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
162
163
    def run(self):
164
        """Create of_core as default napps enabled."""
165
        print(self.description)
166
167
168
# class EggInfo(egg_info):
169
#     """Prepare files to be packed."""
170
#
171
#     def run(self):
172
#         """Build css."""
173
#         self._install_deps_wheels()
174
#         super().run()
175
#
176
#     @staticmethod
177
#     def _install_deps_wheels():
178
#         """Python wheels are much faster (no compiling)."""
179
#         print('Installing dependencies...')
180
#         check_call([sys.executable, '-m', 'pip', 'install', '-r',
181
#                     'requirements/run.in'])
182
183
184
class DevelopMode(develop):
185
    """Recommended setup for kytos-napps developers.
186
187
    Instead of copying the files to the expected directories, a symlink is
188
    created on the system aiming the current source code.
189
    """
190
191
    description = 'install NApps in development mode'
192
193
    def run(self):
194
        """Install the package in a developer mode."""
195
        super().run()
196
        if self.uninstall:
197
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
198
        else:
199
            self._create_folder_symlinks()
200
            # self._create_file_symlinks()
201
            # KytosInstall.enable_core_napps()
202
203
    @staticmethod
204
    def _create_folder_symlinks():
205
        """Symlink to all Kytos NApps folders.
206
207
        ./napps/kytos/napp_name will generate a link in
208
        var/lib/kytos/napps/.installed/kytos/napp_name.
209
        """
210
        links = INSTALLED_PATH / 'kytos'
211
        links.mkdir(parents=True, exist_ok=True)
212
        code = CURRENT_DIR
213
        src = links / 'of_core'
214
        symlink_if_different(src, code)
215
216
        (ENABLED_PATH / 'kytos').mkdir(parents=True, exist_ok=True)
217
        dst = ENABLED_PATH / Path('kytos', 'of_core')
218
        symlink_if_different(dst, src)
219
220
    # @staticmethod
221
    # def _create_file_symlinks():
222
    #     """Symlink to required files."""
223
    #     src = ENABLED_PATH / '__init__.py'
224
    #     dst = CURRENT_DIR / 'napps' / '__init__.py'
225
    #     symlink_if_different(src, dst)
226
227
228
def symlink_if_different(path, target):
229
    """Force symlink creation if it points anywhere else."""
230
    # print(f"symlinking {path} to target: {target}...", end=" ")
231
    if not path.exists():
232
        # print(f"path doesn't exist. linking...")
233
        path.symlink_to(target)
234
    elif not path.samefile(target):
235
        # print(f"path exists, but is different. removing and linking...")
236
        # Exists but points to a different file, so let's replace it
237
        path.unlink()
238
        path.symlink_to(target)
239
240
241
def read_version_from_json():
242
    """Read the NApp version from NApp kytos.json file."""
243
    file = Path('kytos.json')
244
    metadata = json.loads(file.read_text())
245
    return metadata['version']
246
247
248
setup(name='kytos_of_core',
249
      version=read_version_from_json(),
250
      description='Core NApps developed by Kytos Team',
251
      url='http://github.com/kytos/of_core',
252
      author='Kytos Team',
253
      author_email='[email protected]',
254
      license='MIT',
255
      setup_requires=['pytest-runner'],
256
      tests_require=['pytest'],
257
      extras_require={
258
          'dev': [
259
              'coverage',
260
              'pip-tools',
261
              'yala',
262
              'tox',
263
          ],
264
      },
265
      cmdclass={
266
          'clean': Cleaner,
267
          'ci': CITest,
268
          'coverage': TestCoverage,
269
          'develop': DevelopMode,
270
          'install': InstallMode,
271
          'lint': Linter,
272
          # 'egg_info': EggInfo,
273
      },
274
      zip_safe=False,
275
      classifiers=[
276
          'License :: OSI Approved :: MIT License',
277
          'Operating System :: POSIX :: Linux',
278
          'Programming Language :: Python :: 3.6',
279
          'Topic :: System :: Networking',
280
      ])
281