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
|
|
|
|
19
|
|
|
import unittest |
20
|
|
|
from unittest.mock import patch |
21
|
|
|
from io import BytesIO |
22
|
|
|
from pathlib import Path |
23
|
|
|
from lxml import etree |
24
|
|
|
|
25
|
|
|
from gvmtools.script_utils import create_xml_tree, error_and_exit, yes_or_no |
26
|
|
|
|
27
|
|
|
CWD = Path(__file__).absolute().parent |
28
|
|
|
|
29
|
|
|
|
30
|
|
|
class ScriptUtilsTestCase(unittest.TestCase): |
31
|
|
|
@patch('builtins.input', lambda *args: 'y') |
32
|
|
|
def test_yes(self): |
33
|
|
|
yes = yes_or_no('foo?') |
34
|
|
|
self.assertTrue(yes) |
35
|
|
|
|
36
|
|
|
@patch('builtins.input', lambda *args: 'n') |
37
|
|
|
def test_no(self): |
38
|
|
|
no = yes_or_no('bar?') |
39
|
|
|
self.assertFalse(no) |
40
|
|
|
|
41
|
|
|
def test_error_and_exit(self): |
42
|
|
|
with self.assertRaises(SystemExit): |
43
|
|
|
error_and_exit('foo') |
44
|
|
|
|
45
|
|
|
def test_create_xml_tree(self): |
46
|
|
|
tree = create_xml_tree(BytesIO(b'<foo><baz/><bar>glurp</bar></foo>')) |
47
|
|
|
self.assertIsInstance( |
48
|
|
|
tree, etree._Element # pylint: disable=protected-access |
49
|
|
|
) |
50
|
|
|
self.assertEqual(tree.tag, 'foo') |
51
|
|
|
|
52
|
|
|
def test_create_xml_tree_invalid_file(self): |
53
|
|
|
target_xml_path = CWD / 'invalid_file.xml' |
54
|
|
|
|
55
|
|
|
with self.assertRaises(SystemExit): |
56
|
|
|
with self.assertRaises(OSError): |
57
|
|
|
create_xml_tree(str(target_xml_path)) |
58
|
|
|
|
59
|
|
|
def test_create_xml_tree_invalid_xml(self): |
60
|
|
|
with self.assertRaises(SystemExit): |
61
|
|
|
with self.assertRaises(etree.Error): |
62
|
|
|
create_xml_tree(BytesIO(b'<foo><baz/><bar>glurp<bar></foo>')) |
63
|
|
|
|