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