slapformat.py 19.2 KB
Newer Older
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2012 Vifib SARL and Contributors.
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

30 31 32 33
import logging
import slapos.format
import unittest

34
import netaddr
35
import socket
36

37 38
# for mocking
import grp
39
import netifaces
40 41
import os
import pwd
42
import time
43

Łukasz Nowak's avatar
Łukasz Nowak committed
44
USER_LIST = []
Łukasz Nowak's avatar
Łukasz Nowak committed
45
GROUP_LIST = []
46
INTERFACE_DICT = {}
Łukasz Nowak's avatar
Łukasz Nowak committed
47

48 49 50 51 52 53 54 55 56 57 58
class FakeConfig:
  pass

class TestLoggerHandler(logging.Handler):
  def __init__(self, *args, **kwargs):
    self.bucket = []
    logging.Handler.__init__(self, *args, **kwargs)

  def emit(self, record):
    self.bucket.append(record.msg)

Łukasz Nowak's avatar
Łukasz Nowak committed
59 60 61 62 63
class FakeCallAndRead:
  def __init__(self):
    self.external_command_list = []

  def __call__(self, argument_list, raise_on_error=True):
64
    retval = 0, 'UP'
65
    global INTERFACE_DICT
Łukasz Nowak's avatar
Łukasz Nowak committed
66 67 68
    if 'useradd' in argument_list:
      global USER_LIST
      USER_LIST.append(argument_list[-1])
69
    elif 'groupadd' in argument_list:
Łukasz Nowak's avatar
Łukasz Nowak committed
70 71
      global GROUP_LIST
      GROUP_LIST.append(argument_list[-1])
72 73 74 75 76 77
    elif argument_list[:3] == ['ip', 'addr', 'add']:
      ip, interface = argument_list[3], argument_list[5]
      if ':' not in ip:
        netmask = netaddr.strategy.ipv4.int_to_str(
          netaddr.strategy.ipv4.prefix_to_netmask[int(ip.split('/')[1])])
        ip = ip.split('/')[0]
78
        INTERFACE_DICT[interface][socket.AF_INET].append({'addr': ip, 'netmask': netmask})
79 80 81 82
      else:
        netmask = netaddr.strategy.ipv6.int_to_str(
          netaddr.strategy.ipv6.prefix_to_netmask[int(ip.split('/')[1])])
        ip = ip.split('/')[0]
83
        INTERFACE_DICT[interface][socket.AF_INET6].append({'addr': ip, 'netmask': netmask})
84 85 86
      # stabilise by mangling ip to just ip string
      argument_list[3] = 'ip/%s' % netmask
    elif argument_list[:3] == ['ip', 'addr', 'list']:
87
      retval = 0, str(INTERFACE_DICT)
Łukasz Nowak's avatar
Łukasz Nowak committed
88
    self.external_command_list.append(' '.join(argument_list))
89
    return retval
Łukasz Nowak's avatar
Łukasz Nowak committed
90

91 92 93 94 95 96 97 98 99 100
class LoggableWrapper:
  def __init__(self, logger, name):
    self.__logger = logger
    self.__name = name

  def __call__(self, *args, **kwargs):
    arg_list = [repr(x) for x in args] + [
      '%s=%r' % (x, y) for x, y in kwargs.iteritems()]
    self.__logger.debug('%s(%s)' % (self.__name, ', '.join(arg_list)))

101 102 103 104 105
class TimeMock:
  @classmethod
  def sleep(self, seconds):
    return

106 107 108
class GrpMock:
  @classmethod
  def getgrnam(self, name):
Łukasz Nowak's avatar
Łukasz Nowak committed
109 110
    global GROUP_LIST
    if name in GROUP_LIST:
111 112 113 114 115 116
      return True
    raise KeyError

class PwdMock:
  @classmethod
  def getpwnam(self, name):
Łukasz Nowak's avatar
Łukasz Nowak committed
117 118
    global USER_LIST
    if name in USER_LIST:
119 120 121 122 123
      class result:
        pw_uid = 0
        pw_gid = 0
      return result
    raise KeyError
124

125 126 127 128 129 130 131 132 133 134 135 136 137
class NetifacesMock:
  @classmethod
  def ifaddresses(self, name):
    global INTERFACE_DICT
    if name in INTERFACE_DICT:
      return INTERFACE_DICT[name]
    raise ValueError

  @classmethod
  def interfaces(self):
    global INTERFACE_DICT
    return INTERFACE_DICT.keys()

138
class SlapformatMixin(unittest.TestCase):
Łukasz Nowak's avatar
Łukasz Nowak committed
139 140
  # keep big diffs
  maxDiff = None
141 142 143 144 145 146 147 148 149 150 151 152
  def patchNetifaces(self):
    self.netifaces = NetifacesMock()
    self.saved_netifaces = dict()
    for fake in vars(NetifacesMock):
      self.saved_netifaces[fake] = getattr(netifaces, fake, None)
      setattr(netifaces, fake, getattr(self.netifaces, fake))

  def restoreNetifaces(self):
    for name, original_value in self.saved_netifaces.items():
      setattr(netifaces, name, original_value)
    del self.saved_netifaces

153 154 155 156 157 158 159 160 161 162 163
  def patchPwd(self):
    self.saved_pwd = dict()
    for fake in vars(PwdMock):
      self.saved_pwd[fake] = getattr(pwd, fake, None)
      setattr(pwd, fake, getattr(PwdMock, fake))

  def restorePwd(self):
    for name, original_value in self.saved_pwd.items():
      setattr(pwd, name, original_value)
    del self.saved_pwd

164 165 166 167 168 169 170 171 172 173 174
  def patchTime(self):
    self.saved_time = dict()
    for fake in vars(TimeMock):
      self.saved_time[fake] = getattr(time, fake, None)
      setattr(time, fake, getattr(TimeMock, fake))

  def restoreTime(self):
    for name, original_value in self.saved_time.items():
      setattr(time, name, original_value)
    del self.saved_time

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  def patchGrp(self):
    self.saved_grp = dict()
    for fake in vars(GrpMock):
      self.saved_grp[fake] = getattr(grp, fake, None)
      setattr(grp, fake, getattr(GrpMock, fake))

  def restoreGrp(self):
    for name, original_value in self.saved_grp.items():
      setattr(grp, name, original_value)
    del self.saved_grp

  def patchOs(self, logger):
    self.saved_os = dict()
    for fake in ['mkdir', 'chown', 'chmod', 'makedirs']:
      self.saved_os[fake] = getattr(os, fake, None)
      f = LoggableWrapper(logger, fake)
      setattr(os, fake, f)

  def restoreOs(self):
    for name, original_value in self.saved_os.items():
      setattr(os, name, original_value)
    del self.saved_os
Łukasz Nowak's avatar
Łukasz Nowak committed
197

198 199
  def setUp(self):
    config = FakeConfig()
Łukasz Nowak's avatar
Łukasz Nowak committed
200
    config.dry_run = True
201 202 203 204 205 206 207
    config.verbose = True
    logger = logging.getLogger('testcatch')
    logger.setLevel(logging.DEBUG)
    self.test_result = TestLoggerHandler()
    logger.addHandler(self.test_result)
    config.logger = logger
    self.partition = slapos.format.Partition('partition', '/part_path',
208
      slapos.format.User('testuser'), [], None)
Łukasz Nowak's avatar
Łukasz Nowak committed
209
    global USER_LIST
Łukasz Nowak's avatar
Łukasz Nowak committed
210 211 212
    USER_LIST = []
    global GROUP_LIST
    GROUP_LIST = []
213 214
    global INTERFACE_DICT
    INTERFACE_DICT = {}
Łukasz Nowak's avatar
Łukasz Nowak committed
215

Łukasz Nowak's avatar
Łukasz Nowak committed
216
    self.real_callAndRead = slapos.format.callAndRead
Łukasz Nowak's avatar
Łukasz Nowak committed
217 218
    self.fakeCallAndRead = FakeCallAndRead()
    slapos.format.callAndRead = self.fakeCallAndRead
219 220
    self.patchOs(logger)
    self.patchGrp()
221
    self.patchTime()
222
    self.patchPwd()
223
    self.patchNetifaces()
Łukasz Nowak's avatar
Łukasz Nowak committed
224 225

  def tearDown(self):
226 227
    self.restoreOs()
    self.restoreGrp()
228
    self.restoreTime()
229
    self.restorePwd()
230
    self.restoreNetifaces()
Łukasz Nowak's avatar
Łukasz Nowak committed
231 232 233 234 235 236 237
    slapos.format.callAndRead = self.real_callAndRead

class TestComputer(SlapformatMixin):
  def test_getAddress_empty_computer(self):
    computer = slapos.format.Computer('computer')
    self.assertEqual(computer.getAddress(), {'netmask': None, 'addr': None})

238
  @unittest.skip("Not implemented")
Łukasz Nowak's avatar
Łukasz Nowak committed
239 240 241 242
  def test_construct_empty(self):
    computer = slapos.format.Computer('computer')
    computer.construct()

243
  @unittest.skip("Not implemented")
244 245
  def test_construct_empty_prepared(self):
    computer = slapos.format.Computer('computer',
246
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
247 248 249 250 251 252 253 254 255
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    computer.construct()
    self.assertEqual([
      "makedirs('/instance_root', 493)",
      "makedirs('/software_root', 493)",
      "chown('/software_root', 0, 0)",
      "chmod('/software_root', 493)"],
      self.test_result.bucket)
Łukasz Nowak's avatar
Łukasz Nowak committed
256
    self.assertEqual([
Łukasz Nowak's avatar
Łukasz Nowak committed
257 258
      'ip addr list bridge',
      'groupadd slapsoft',
259
      'useradd -d /software_root -g slapsoft -s /bin/false slapsoft -r'
Łukasz Nowak's avatar
Łukasz Nowak committed
260
      ],
Łukasz Nowak's avatar
Łukasz Nowak committed
261
      self.fakeCallAndRead.external_command_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
262 263 264

  def test_construct_empty_prepared_no_alter_user(self):
    computer = slapos.format.Computer('computer',
265
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
Łukasz Nowak's avatar
Łukasz Nowak committed
266 267 268 269 270 271 272 273 274
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    computer.construct(alter_user=False)
    self.assertEqual([
      "makedirs('/instance_root', 493)",
      "makedirs('/software_root', 493)",
      "chmod('/software_root', 493)"],
      self.test_result.bucket)
    self.assertEqual([
Łukasz Nowak's avatar
Łukasz Nowak committed
275
      'ip addr list bridge',],
Łukasz Nowak's avatar
Łukasz Nowak committed
276
      self.fakeCallAndRead.external_command_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
277

278
  @unittest.skip("Not implemented")
Łukasz Nowak's avatar
Łukasz Nowak committed
279 280
  def test_construct_empty_prepared_no_alter_network(self):
    computer = slapos.format.Computer('computer',
281
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
Łukasz Nowak's avatar
Łukasz Nowak committed
282 283 284 285 286 287 288 289 290 291
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    computer.construct(alter_network=False)
    self.assertEqual([
      "makedirs('/instance_root', 493)",
      "makedirs('/software_root', 493)",
      "chown('/software_root', 0, 0)",
      "chmod('/software_root', 493)"],
      self.test_result.bucket)
    self.assertEqual([
Łukasz Nowak's avatar
Łukasz Nowak committed
292 293
      'ip addr list bridge',
      'groupadd slapsoft',
294
      'useradd -d /software_root -g slapsoft -s /bin/false slapsoft -r'
Łukasz Nowak's avatar
Łukasz Nowak committed
295
      ],
Łukasz Nowak's avatar
Łukasz Nowak committed
296
      self.fakeCallAndRead.external_command_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
297 298 299

  def test_construct_empty_prepared_no_alter_network_user(self):
    computer = slapos.format.Computer('computer',
300
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
Łukasz Nowak's avatar
Łukasz Nowak committed
301 302 303 304 305 306 307 308 309
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    computer.construct(alter_network=False, alter_user=False)
    self.assertEqual([
      "makedirs('/instance_root', 493)",
      "makedirs('/software_root', 493)",
      "chmod('/software_root', 493)"],
      self.test_result.bucket)
    self.assertEqual([
Łukasz Nowak's avatar
Łukasz Nowak committed
310
      'ip addr list bridge',
Łukasz Nowak's avatar
Łukasz Nowak committed
311
      ],
Łukasz Nowak's avatar
Łukasz Nowak committed
312
      self.fakeCallAndRead.external_command_list)
313

314
  @unittest.skip("Not implemented")
315 316
  def test_construct_prepared(self):
    computer = slapos.format.Computer('computer',
317
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
318 319 320 321 322 323 324 325
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    partition = slapos.format.Partition('partition', '/part_path',
      slapos.format.User('testuser'), [], None)
    partition.tap = slapos.format.Tap('tap')
    computer.partition_list = [partition]
    global INTERFACE_DICT
    INTERFACE_DICT['bridge'] = {
326
      socket.AF_INET: [{'addr': '192.168.242.77', 'broadcast': '127.0.0.1',
327
        'netmask': '255.255.255.0'}],
328
      socket.AF_INET6: [{'addr': '2a01:e35:2e27::e59c', 'netmask': 'ffff:ffff:ffff:ffff::'}]
329 330 331 332 333 334 335 336 337 338 339 340 341 342
    }

    computer.construct()
    self.assertEqual([
      "makedirs('/instance_root', 493)",
      "makedirs('/software_root', 493)",
      "chown('/software_root', 0, 0)",
      "chmod('/software_root', 493)",
      "mkdir('/instance_root/partition', 488)",
      "chown('/instance_root/partition', 0, 0)",
      "chmod('/instance_root/partition', 488)"
    ],
      self.test_result.bucket)
    self.assertEqual([
Łukasz Nowak's avatar
Łukasz Nowak committed
343 344
      'ip addr list bridge',
      'groupadd slapsoft',
345
      'useradd -d /software_root -g slapsoft -s /bin/false slapsoft -r',
Łukasz Nowak's avatar
Łukasz Nowak committed
346
      'groupadd testuser',
347
      'useradd -d /instance_root/partition -g testuser -s /bin/false -G slapsoft testuser -r',
Łukasz Nowak's avatar
Łukasz Nowak committed
348 349 350 351 352 353 354 355
      'tunctl -t tap -u testuser',
      'ip link set tap up',
      'brctl show',
      'brctl addif bridge tap',
      'ip addr add ip/255.255.255.255 dev bridge',
      'ip addr list bridge',
      'ip addr add ip/ffff:ffff:ffff:ffff:: dev bridge',
      'ip addr list bridge',
356 357 358 359 360
    ],
      self.fakeCallAndRead.external_command_list)

  def test_construct_prepared_no_alter_user(self):
    computer = slapos.format.Computer('computer',
361
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
362 363 364 365
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    partition = slapos.format.Partition('partition', '/part_path',
      slapos.format.User('testuser'), [], None)
366 367
    global USER_LIST
    USER_LIST=['testuser']
368 369 370 371
    partition.tap = slapos.format.Tap('tap')
    computer.partition_list = [partition]
    global INTERFACE_DICT
    INTERFACE_DICT['bridge'] = {
372
      socket.AF_INET: [{'addr': '192.168.242.77', 'broadcast': '127.0.0.1',
373
        'netmask': '255.255.255.0'}],
374
      socket.AF_INET6: [{'addr': '2a01:e35:2e27::e59c', 'netmask': 'ffff:ffff:ffff:ffff::'}]
375 376 377 378 379 380 381 382 383 384 385 386
    }

    computer.construct(alter_user=False)
    self.assertEqual([
      "makedirs('/instance_root', 493)",
      "makedirs('/software_root', 493)",
      "chmod('/software_root', 493)",
      "mkdir('/instance_root/partition', 488)",
      "chmod('/instance_root/partition', 488)"
    ],
      self.test_result.bucket)
    self.assertEqual([
Łukasz Nowak's avatar
Łukasz Nowak committed
387
      'ip addr list bridge',
388
      'tunctl -t tap -u testuser',
Łukasz Nowak's avatar
Łukasz Nowak committed
389 390 391 392
      'ip link set tap up',
      'brctl show',
      'brctl addif bridge tap',
      'ip addr add ip/255.255.255.255 dev bridge',
393
#      'ip addr list bridge',
Łukasz Nowak's avatar
Łukasz Nowak committed
394 395
      'ip addr add ip/ffff:ffff:ffff:ffff:: dev bridge',
      'ip addr list bridge',
396 397 398
    ],
      self.fakeCallAndRead.external_command_list)

399
  @unittest.skip("Not implemented")
400 401
  def test_construct_prepared_no_alter_network(self):
    computer = slapos.format.Computer('computer',
402
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
403 404 405 406 407 408 409 410
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    partition = slapos.format.Partition('partition', '/part_path',
      slapos.format.User('testuser'), [], None)
    partition.tap = slapos.format.Tap('tap')
    computer.partition_list = [partition]
    global INTERFACE_DICT
    INTERFACE_DICT['bridge'] = {
411
      socket.AF_INET: [{'addr': '192.168.242.77', 'broadcast': '127.0.0.1',
412
        'netmask': '255.255.255.0'}],
413
      socket.AF_INET6: [{'addr': '2a01:e35:2e27::e59c', 'netmask': 'ffff:ffff:ffff:ffff::'}]
414 415 416 417 418 419 420 421 422 423 424 425 426 427
    }

    computer.construct(alter_network=False)
    self.assertEqual([
      "makedirs('/instance_root', 493)",
      "makedirs('/software_root', 493)",
      "chown('/software_root', 0, 0)",
      "chmod('/software_root', 493)",
      "mkdir('/instance_root/partition', 488)",
      "chown('/instance_root/partition', 0, 0)",
      "chmod('/instance_root/partition', 488)"
    ],
      self.test_result.bucket)
    self.assertEqual([
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
428
      # 'ip addr list bridge',
Łukasz Nowak's avatar
Łukasz Nowak committed
429
      'groupadd slapsoft',
430
      'useradd -d /software_root -g slapsoft -s /bin/false slapsoft -r',
Łukasz Nowak's avatar
Łukasz Nowak committed
431
      'groupadd testuser',
432
      'useradd -d /instance_root/partition -g testuser -s /bin/false -G slapsoft testuser -r',
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
433 434 435 436
      # 'ip addr add ip/255.255.255.255 dev bridge',
      # 'ip addr list bridge',
      # 'ip addr add ip/ffff:ffff:ffff:ffff:: dev bridge',
      # 'ip addr list bridge',
437 438 439 440 441
    ],
      self.fakeCallAndRead.external_command_list)

  def test_construct_prepared_no_alter_network_user(self):
    computer = slapos.format.Computer('computer',
442
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
443 444 445 446 447 448 449 450
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    partition = slapos.format.Partition('partition', '/part_path',
      slapos.format.User('testuser'), [], None)
    partition.tap = slapos.format.Tap('tap')
    computer.partition_list = [partition]
    global INTERFACE_DICT
    INTERFACE_DICT['bridge'] = {
451
      socket.AF_INET: [{'addr': '192.168.242.77', 'broadcast': '127.0.0.1',
452
        'netmask': '255.255.255.0'}],
453
      socket.AF_INET6: [{'addr': '2a01:e35:2e27::e59c', 'netmask': 'ffff:ffff:ffff:ffff::'}]
454 455 456 457 458 459 460 461 462 463 464 465
    }

    computer.construct(alter_network=False, alter_user=False)
    self.assertEqual([
      "makedirs('/instance_root', 493)",
      "makedirs('/software_root', 493)",
      "chmod('/software_root', 493)",
      "mkdir('/instance_root/partition', 488)",
      "chmod('/instance_root/partition', 488)"
    ],
      self.test_result.bucket)
    self.assertEqual([
466 467
      'ip addr list bridge',
      'ip addr add ip/255.255.255.255 dev bridge',
468
#      'ip addr list bridge',
469 470
      'ip addr add ip/ffff:ffff:ffff:ffff:: dev bridge',
      'ip addr list bridge',
471 472 473
    ],
      self.fakeCallAndRead.external_command_list)

Łukasz Nowak's avatar
Łukasz Nowak committed
474
class TestPartition(SlapformatMixin):
475 476

  def test_createPath(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
477 478
    global USER_LIST
    USER_LIST = ['testuser']
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    self.partition.createPath()
    self.assertEqual(
      [
        "mkdir('/part_path', 488)",
        "chown('/part_path', 0, 0)",
        "chmod('/part_path', 488)"
      ],
      self.test_result.bucket
    )

  def test_createPath_no_alter_user(self):
    self.partition.createPath(False)
    self.assertEqual(
      [
        "mkdir('/part_path', 488)",
        "chmod('/part_path', 488)"
      ],
      self.test_result.bucket
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
499
class TestUser(SlapformatMixin):
500
  def test_create(self):
501 502
    user = slapos.format.User('doesnotexistsyet')
    user.setPath('/doesnotexistsyet')
503 504
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
505 506 507
    self.assertEqual([
      'groupadd doesnotexistsyet',
      'useradd -d /doesnotexistsyet -g doesnotexistsyet -s /bin/false '\
508
        'doesnotexistsyet -r'
Łukasz Nowak's avatar
Łukasz Nowak committed
509
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
510
      self.fakeCallAndRead.external_command_list)
511 512

  def test_create_additional_groups(self):
513
    user = slapos.format.User('doesnotexistsyet', ['additionalgroup1',
514
      'additionalgroup2'])
515
    user.setPath('/doesnotexistsyet')
516 517
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
518 519 520
    self.assertEqual([
      'groupadd doesnotexistsyet',
      'useradd -d /doesnotexistsyet -g doesnotexistsyet -s /bin/false -G '\
521
        'additionalgroup1,additionalgroup2 doesnotexistsyet -r'
522
      ],
Łukasz Nowak's avatar
Łukasz Nowak committed
523
      self.fakeCallAndRead.external_command_list)
524 525

  def test_create_group_exists(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
526 527
    global GROUP_LIST
    GROUP_LIST = ['testuser']
528 529 530 531
    user = slapos.format.User('testuser')
    user.setPath('/testuser')
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
532
    self.assertEqual([
533
      'useradd -d /testuser -g testuser -s /bin/false testuser -r'
Łukasz Nowak's avatar
Łukasz Nowak committed
534
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
535
      self.fakeCallAndRead.external_command_list)
536 537

  def test_create_user_exists_additional_groups(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
538 539
    global USER_LIST
    USER_LIST = ['testuser']
540 541 542 543 544
    user = slapos.format.User('testuser', ['additionalgroup1',
      'additionalgroup2'])
    user.setPath('/testuser')
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
545 546 547 548 549
    self.assertEqual([
      'groupadd testuser',
      'usermod -d /testuser -g testuser -s /bin/false -G '\
        'additionalgroup1,additionalgroup2 testuser'
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
550
      self.fakeCallAndRead.external_command_list)
551 552

  def test_create_user_exists(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
553 554
    global USER_LIST
    USER_LIST = ['testuser']
555 556 557 558
    user = slapos.format.User('testuser')
    user.setPath('/testuser')
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
559 560 561 562
    self.assertEqual([
      'groupadd testuser',
      'usermod -d /testuser -g testuser -s /bin/false testuser'
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
563
      self.fakeCallAndRead.external_command_list)
564 565

  def test_create_user_group_exists(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
566 567 568 569
    global USER_LIST
    USER_LIST = ['testuser']
    global GROUP_LIST
    GROUP_LIST = ['testuser']
570 571 572 573
    user = slapos.format.User('testuser')
    user.setPath('/testuser')
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
574 575 576
    self.assertEqual([
      'usermod -d /testuser -g testuser -s /bin/false testuser'
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
577
      self.fakeCallAndRead.external_command_list)
578 579

  def test_isAvailable(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
580 581
    global USER_LIST
    USER_LIST = ['testuser']
582 583 584 585
    user = slapos.format.User('testuser')
    self.assertTrue(user.isAvailable())

  def test_isAvailable_notAvailable(self):
586
    user = slapos.format.User('doesnotexistsyet')
587 588 589 590
    self.assertFalse(user.isAvailable())

if __name__ == '__main__':
      unittest.main()