Passed
Push — master ( ce2058...63ffa0 )
by Humberto
03:14 queued 19s
created

build.setup.TestCommand.get_args()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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