Completed
Push — master ( 39c324...8e798a )
by Jaspar
14s queued 10s
created

AuthenticateTestCase.test_authenticate()   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2020 Greenbone Networks GmbH
3
#
4
# SPDX-License-Identifier: GPL-3.0-or-later
5
#
6
# This program is free software: you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation, either version 3 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
import sys
19
import unittest
20
from unittest import mock
21
22
from gvm.errors import GvmError
23
24
from gvmtools.helper import Table, do_not_run_as_root, authenticate, run_script
25
26
27
class TableTestCase(unittest.TestCase):
28
    def setUp(self):
29
        self.heading = ['ID', 'Name', 'Severity']
30
        self.rows = [
31
            ['1', 'foobar', 'high'],
32
            ['2', 'bla', 'low'],
33
            ['3', 'blub', 'medium'],
34
        ]
35
        self.divider = ' - '
36
37
        self.table = Table(
38
            heading=self.heading, rows=self.rows, divider=self.divider
39
        )
40
41
    def test_init_no_args(self):
42
        table = Table()
43
44
        self.assertListEqual(table.heading, [])
45
        self.assertListEqual(table.rows, [])
46
        self.assertEqual(table.divider, ' | ')
47
48
    def test_init_with_args(self):
49
        self.assertListEqual(self.table.heading, self.heading)
50
        self.assertListEqual(self.table.rows, self.rows)
51
        self.assertEqual(self.table.divider, self.divider)
52
53
    def test_calculate_dimensions(self):
54
        expected_result = [
55
            len(self.heading[0]),
56
            len(self.rows[0][1]),
57
            len(self.heading[2]),
58
        ]
59
60
        column_sizes = (
61
            self.table._calculate_dimensions()  # pylint: disable=protected-access
62
        )
63
64
        self.assertEqual(column_sizes, expected_result)
65
66
    def test_create_column(self):
67
        column = 'foobar'
68
        size = 20
69
        expected = 'foobar              '
70
71
        result = self.table._create_column(  # pylint: disable=protected-access
72
            column, size
73
        )
74
75
        self.assertEqual(result, expected)
76
77
    def test_create_row(self):
78
        columns = ['foo', 'bar', 'blub']
79
        expected = self.divider.join(columns)
80
81
        result = self.table._create_row(columns)  # pylint: disable=W0212
82
83
        self.assertEqual(result, expected)
84
85
    def test_str(self):
86
        expected = (
87
            'ID - Name   - Severity\n'
88
            + '-- - ------ - --------\n'
89
            + '1  - foobar - high    \n'
90
            + '2  - bla    - low     \n'
91
            + '3  - blub   - medium  '
92
        )
93
94
        self.assertEqual(str(self.table), expected)
95
96
97
class DoNotRunAsRootTestCase(unittest.TestCase):
98
    @mock.patch('gvmtools.helper.os')
99
    def test_do_not_run_as_root_as_root(self, mock_os):
100
        mock_os.geteuid = unittest.mock.MagicMock(spec='geteuid')
101
        mock_os.geteuid.return_value = 0
102
103
        self.assertRaises(RuntimeError, do_not_run_as_root)
104
105
    @mock.patch('gvmtools.helper.os')
106
    def test_do_not_run_as_root_as_non_root(self, mock_os):
107
        mock_os.geteuid = unittest.mock.MagicMock(spec='geteuid')
108
        mock_os.geteuid.return_value = 123
109
110
        self.assertIsNone(do_not_run_as_root())
111
112
113
class AuthenticateTestCase(unittest.TestCase):
114
    def test_authenticate_already_authenticated(self):
115
        mock_gmp = self.create_gmp_mock(True)
116
117
        self.assertIsNone(authenticate(mock_gmp))
118
119
    @mock.patch('gvmtools.helper.input', return_value='foo')
120
    def test_authenticate_username_is_none(
121
        self, mock_input
122
    ):  # pylint: disable=unused-argument,line-too-long
123
        mock_gmp = self.create_gmp_mock(False)
124
125
        return_value = authenticate(mock_gmp, password='bar')
126
127
        self.assertTrue(isinstance(return_value, tuple))
128
        self.assertEqual(return_value[0], 'foo')
129
        self.assertEqual(return_value[1], 'bar')
130
131
    @mock.patch('gvmtools.helper.getpass')
132
    def test_authenticate_password_is_none(self, mock_getpass):
133
        mock_gmp = self.create_gmp_mock(False)
134
        mock_getpass.getpass = mock.MagicMock(return_value='SuperSecret123!')
135
136
        return_value = authenticate(mock_gmp, username='user')
137
138
        self.assertTrue(isinstance(return_value, tuple))
139
        self.assertEqual(return_value[0], 'user')
140
        self.assertEqual(return_value[1], 'SuperSecret123!')
141
142
    def test_authenticate(self):
143
        mock_gmp = self.create_gmp_mock(False)
144
145
        return_value = authenticate(
146
            mock_gmp, username='user', password='password'
147
        )
148
149
        self.assertTrue(isinstance(return_value, tuple))
150
        self.assertEqual(return_value[0], 'user')
151
        self.assertEqual(return_value[1], 'password')
152
153
    def test_authenticate_bad_credentials(self):
154
        mock_gmp = self.create_gmp_mock(False)
155
156
        def my_authenticate(username, password):
157
            raise GvmError('foo')
158
159
        mock_gmp.authenticate = my_authenticate
160
161
        self.assertRaises(GvmError, authenticate, mock_gmp, 'user', 'password')
162
163
    def create_gmp_mock(self, authenticated_return_value):
164
        mock_gmp = mock.MagicMock()
165
        mock_gmp.is_authenticated = mock.MagicMock(
166
            return_value=authenticated_return_value
167
        )
168
        return mock_gmp
169
170
171
class RunScriptTestCase(unittest.TestCase):
172
    @mock.patch('gvmtools.helper.open')
173
    @mock.patch('gvmtools.helper.exec')
174
    def test_run_script(self, mock_exec, mock_open):
175
        path = 'foo'
176
        global_vars = ['OpenVAS', 'is', 'awesome']
177
        mock_open().read.return_value = 'file content'
178
179
        run_script(path, global_vars)
180
181
        mock_open.assert_called_with(path, 'r', newline='')
182
        mock_exec.assert_called_with('file content', global_vars)
183
184
    @mock.patch('gvmtools.helper.open')
185
    @mock.patch('gvmtools.helper.print')
186
    def test_run_script_file_not_found(self, mock_print, mock_open):
187
        def my_open(path, mode, newline):
188
            raise FileNotFoundError
189
190
        mock_open.side_effect = my_open
191
192
        path = 'foo'
193
        global_vars = ['OpenVAS', 'is', 'awesome']
194
195
        with self.assertRaises(SystemExit):
196
            run_script(path, global_vars)
197
198
        mock_print.assert_called_with(
199
            'Script {path} does not exist'.format(path=path), file=sys.stderr
200
        )
201