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