Completed
Pull Request — master (#69)
by Gleyberson
02:18
created

build.setup.TestCommand.finalize_options()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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