Add a natural sort key function
[wifi-radar.git] / test / unit / misc.py
blob9a5e9b312b22627cc3b3198bbc462a2f158080ee
1 # test.misc - tests for miscellaneous functions
3 # Part of WiFi Radar: A utility for managing WiFi profiles on GNU/Linux.
5 # Copyright (C) 2014 Sean Robinson <robinson@tuxfamily.org>
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; version 2 of the License.
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 in LICENSE.GPL for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to:
18 # Free Software Foundation, Inc.
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 from __future__ import unicode_literals
25 import random
26 from subprocess import CalledProcessError
27 import unittest
29 import mock
31 import wifiradar.misc as misc
34 class TestFunctions(unittest.TestCase):
36 @mock.patch.dict('wifiradar.misc.os.environ', clear=True)
37 @mock.patch('wifiradar.misc.check_call')
38 def test_shellcmd(self, mock_call):
39 """ Test shellcmd function. """
40 # Test successful return and custom environment.
41 mock_call.return_value = 0
42 self.assertEqual(0, misc.shellcmd('return0', {'WRv': '2.0'}))
43 mock_call.assert_called_with('return0', shell=True,
44 env={'WRv': '2.0'})
45 # Test for check_call failure.
46 mock_call.side_effect = CalledProcessError(2, 'return2')
47 with self.assertRaises(CalledProcessError) as cm:
48 misc.shellcmd('return2', {})
49 self.assertEqual(2, cm.exception.returncode)
50 self.assertEqual('return2', cm.exception.cmd)
52 def test_natural_sort_key(self):
53 """ Test natural_sort_key function. """
54 # Check every permutation of '12ab' up to 4 characters long.
55 # '1a' < '12' because one-a is less than twelve-a
56 expected = ['1', '1a', '1a2', '1a2b', '1ab', '1ab2', '1b', '1b2',
57 '1b2a', '1ba', '1ba2', '2', '2a', '2a1', '2a1b',
58 '2ab', '2ab1', '2b', '2b1', '2b1a', '2ba', '2ba1',
59 '12', '12a', '12ab', '12b', '12ba', '21', '21a',
60 '21ab', '21b', '21ba', 'a', 'a1', 'a1b', 'a1b2',
61 'a2', 'a2b', 'a2b1', 'a12', 'a12b', 'a21', 'a21b',
62 'ab', 'ab1', 'ab2', 'ab12', 'ab21', 'b', 'b1', 'b1a',
63 'b1a2', 'b2', 'b2a', 'b2a1', 'b12', 'b12a', 'b21',
64 'b21a', 'ba', 'ba1', 'ba2', 'ba12', 'ba21']
65 original = list(expected)
66 random.shuffle(original)
67 # Check that original is no longer a true copy of expected.
68 # Otherwise, our later test is meaningless.
69 self.assertNotEqual(expected, original)
70 result = sorted(original, key=misc.natural_sort_key)
71 self.assertEqual(expected, result)