slapformat.py 17.7 KB
Newer Older
1 2 3 4
import logging
import slapos.format
import unittest

5 6
import netaddr

7 8
# for mocking
import grp
9
import netifaces
10 11
import os
import pwd
12
import time
13

Łukasz Nowak's avatar
Łukasz Nowak committed
14
USER_LIST = []
Łukasz Nowak's avatar
Łukasz Nowak committed
15
GROUP_LIST = []
16
INTERFACE_DICT = {}
Łukasz Nowak's avatar
Łukasz Nowak committed
17

18 19 20 21 22 23 24 25 26 27 28
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
29 30 31 32 33
class FakeCallAndRead:
  def __init__(self):
    self.external_command_list = []

  def __call__(self, argument_list, raise_on_error=True):
34
    retval = 0, 'UP'
35
    global INTERFACE_DICT
Łukasz Nowak's avatar
Łukasz Nowak committed
36 37 38
    if 'useradd' in argument_list:
      global USER_LIST
      USER_LIST.append(argument_list[-1])
39
    elif 'groupadd' in argument_list:
Łukasz Nowak's avatar
Łukasz Nowak committed
40 41
      global GROUP_LIST
      GROUP_LIST.append(argument_list[-1])
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    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]
        INTERFACE_DICT[interface][2].append({'addr': ip, 'netmask': netmask})
      else:
        netmask = netaddr.strategy.ipv6.int_to_str(
          netaddr.strategy.ipv6.prefix_to_netmask[int(ip.split('/')[1])])
        ip = ip.split('/')[0]
        INTERFACE_DICT[interface][10].append({'addr': ip, 'netmask': netmask})
      # stabilise by mangling ip to just ip string
      argument_list[3] = 'ip/%s' % netmask
    elif argument_list[:3] == ['ip', 'addr', 'list']:
57
      retval = 0, str(INTERFACE_DICT)
Łukasz Nowak's avatar
Łukasz Nowak committed
58
    self.external_command_list.append(' '.join(argument_list))
59
    return retval
Łukasz Nowak's avatar
Łukasz Nowak committed
60

61 62 63 64 65 66 67 68 69 70
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)))

71 72 73 74 75
class TimeMock:
  @classmethod
  def sleep(self, seconds):
    return

76 77 78
class GrpMock:
  @classmethod
  def getgrnam(self, name):
Łukasz Nowak's avatar
Łukasz Nowak committed
79 80
    global GROUP_LIST
    if name in GROUP_LIST:
81 82 83 84 85 86
      return True
    raise KeyError

class PwdMock:
  @classmethod
  def getpwnam(self, name):
Łukasz Nowak's avatar
Łukasz Nowak committed
87 88
    global USER_LIST
    if name in USER_LIST:
89 90 91 92 93
      class result:
        pw_uid = 0
        pw_gid = 0
      return result
    raise KeyError
94

95 96 97 98 99 100 101 102 103 104 105 106 107
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()

108
class SlapformatMixin(unittest.TestCase):
Łukasz Nowak's avatar
Łukasz Nowak committed
109 110
  # keep big diffs
  maxDiff = None
111 112 113 114 115 116 117 118 119 120 121 122
  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

123 124 125 126 127 128 129 130 131 132 133
  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

134 135 136 137 138 139 140 141 142 143 144
  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

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  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
167

168 169
  def setUp(self):
    config = FakeConfig()
Łukasz Nowak's avatar
Łukasz Nowak committed
170
    config.dry_run = True
171 172 173 174 175 176 177
    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',
178
      slapos.format.User('testuser'), [], None)
Łukasz Nowak's avatar
Łukasz Nowak committed
179
    global USER_LIST
Łukasz Nowak's avatar
Łukasz Nowak committed
180 181 182
    USER_LIST = []
    global GROUP_LIST
    GROUP_LIST = []
183 184
    global INTERFACE_DICT
    INTERFACE_DICT = {}
Łukasz Nowak's avatar
Łukasz Nowak committed
185

Łukasz Nowak's avatar
Łukasz Nowak committed
186
    self.real_callAndRead = slapos.format.callAndRead
Łukasz Nowak's avatar
Łukasz Nowak committed
187 188
    self.fakeCallAndRead = FakeCallAndRead()
    slapos.format.callAndRead = self.fakeCallAndRead
189 190
    self.patchOs(logger)
    self.patchGrp()
191
    self.patchTime()
192
    self.patchPwd()
193
    self.patchNetifaces()
Łukasz Nowak's avatar
Łukasz Nowak committed
194 195

  def tearDown(self):
196 197
    self.restoreOs()
    self.restoreGrp()
198
    self.restoreTime()
199
    self.restorePwd()
200
    self.restoreNetifaces()
Łukasz Nowak's avatar
Łukasz Nowak committed
201 202 203 204 205 206 207
    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})

208
  @unittest.skip("Not implemented")
Łukasz Nowak's avatar
Łukasz Nowak committed
209 210 211 212
  def test_construct_empty(self):
    computer = slapos.format.Computer('computer')
    computer.construct()

213
  @unittest.skip("Not implemented")
214 215
  def test_construct_empty_prepared(self):
    computer = slapos.format.Computer('computer',
216
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
217 218 219 220 221 222 223 224 225
    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
226
    self.assertEqual([
Łukasz Nowak's avatar
Łukasz Nowak committed
227 228
      'ip addr list bridge',
      'groupadd slapsoft',
229
      'useradd -d /software_root -g slapsoft -s /bin/false slapsoft -r'
Łukasz Nowak's avatar
Łukasz Nowak committed
230
      ],
Łukasz Nowak's avatar
Łukasz Nowak committed
231
      self.fakeCallAndRead.external_command_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
232 233 234

  def test_construct_empty_prepared_no_alter_user(self):
    computer = slapos.format.Computer('computer',
235
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
Łukasz Nowak's avatar
Łukasz Nowak committed
236 237 238 239 240 241 242 243 244
    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
245
      'ip addr list bridge',],
Łukasz Nowak's avatar
Łukasz Nowak committed
246
      self.fakeCallAndRead.external_command_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
247

248
  @unittest.skip("Not implemented")
Łukasz Nowak's avatar
Łukasz Nowak committed
249 250
  def test_construct_empty_prepared_no_alter_network(self):
    computer = slapos.format.Computer('computer',
251
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
Łukasz Nowak's avatar
Łukasz Nowak committed
252 253 254 255 256 257 258 259 260 261
    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
262 263
      'ip addr list bridge',
      'groupadd slapsoft',
264
      'useradd -d /software_root -g slapsoft -s /bin/false slapsoft -r'
Łukasz Nowak's avatar
Łukasz Nowak committed
265
      ],
Łukasz Nowak's avatar
Łukasz Nowak committed
266
      self.fakeCallAndRead.external_command_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
267 268 269

  def test_construct_empty_prepared_no_alter_network_user(self):
    computer = slapos.format.Computer('computer',
270
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
Łukasz Nowak's avatar
Łukasz Nowak committed
271 272 273 274 275 276 277 278 279
    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
280
      'ip addr list bridge',
Łukasz Nowak's avatar
Łukasz Nowak committed
281
      ],
Łukasz Nowak's avatar
Łukasz Nowak committed
282
      self.fakeCallAndRead.external_command_list)
283

284
  @unittest.skip("Not implemented")
285 286
  def test_construct_prepared(self):
    computer = slapos.format.Computer('computer',
287
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    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'] = {
      2: [{'addr': '192.168.242.77', 'broadcast': '127.0.0.1',
        'netmask': '255.255.255.0'}],
      10: [{'addr': '2a01:e35:2e27::e59c', 'netmask': 'ffff:ffff:ffff:ffff::'}]
    }

    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
313 314
      'ip addr list bridge',
      'groupadd slapsoft',
315
      'useradd -d /software_root -g slapsoft -s /bin/false slapsoft -r',
Łukasz Nowak's avatar
Łukasz Nowak committed
316
      'groupadd testuser',
317
      'useradd -d /instance_root/partition -g testuser -s /bin/false -G slapsoft testuser -r',
Łukasz Nowak's avatar
Łukasz Nowak committed
318 319 320 321 322 323 324 325
      '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',
326 327 328 329 330
    ],
      self.fakeCallAndRead.external_command_list)

  def test_construct_prepared_no_alter_user(self):
    computer = slapos.format.Computer('computer',
331
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
332 333 334 335
    computer.instance_root = '/instance_root'
    computer.software_root = '/software_root'
    partition = slapos.format.Partition('partition', '/part_path',
      slapos.format.User('testuser'), [], None)
336 337
    global USER_LIST
    USER_LIST=['testuser']
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    partition.tap = slapos.format.Tap('tap')
    computer.partition_list = [partition]
    global INTERFACE_DICT
    INTERFACE_DICT['bridge'] = {
      2: [{'addr': '192.168.242.77', 'broadcast': '127.0.0.1',
        'netmask': '255.255.255.0'}],
      10: [{'addr': '2a01:e35:2e27::e59c', 'netmask': 'ffff:ffff:ffff:ffff::'}]
    }

    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
357 358 359 360 361 362 363 364 365
      'ip addr list bridge',
      'tunctl -t tap -u root',
      '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',
366 367 368
    ],
      self.fakeCallAndRead.external_command_list)

369
  @unittest.skip("Not implemented")
370 371
  def test_construct_prepared_no_alter_network(self):
    computer = slapos.format.Computer('computer',
372
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    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'] = {
      2: [{'addr': '192.168.242.77', 'broadcast': '127.0.0.1',
        'netmask': '255.255.255.0'}],
      10: [{'addr': '2a01:e35:2e27::e59c', 'netmask': 'ffff:ffff:ffff:ffff::'}]
    }

    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
398
      # 'ip addr list bridge',
Łukasz Nowak's avatar
Łukasz Nowak committed
399
      'groupadd slapsoft',
400
      'useradd -d /software_root -g slapsoft -s /bin/false slapsoft -r',
Łukasz Nowak's avatar
Łukasz Nowak committed
401
      'groupadd testuser',
402
      '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
403 404 405 406
      # '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',
407 408 409 410 411
    ],
      self.fakeCallAndRead.external_command_list)

  def test_construct_prepared_no_alter_network_user(self):
    computer = slapos.format.Computer('computer',
412
      interface=slapos.format.Interface('bridge', '127.0.0.1/16'))
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    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'] = {
      2: [{'addr': '192.168.242.77', 'broadcast': '127.0.0.1',
        'netmask': '255.255.255.0'}],
      10: [{'addr': '2a01:e35:2e27::e59c', 'netmask': 'ffff:ffff:ffff:ffff::'}]
    }

    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([
436 437 438 439 440
#      'ip addr list bridge',
#      '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',
441 442 443
    ],
      self.fakeCallAndRead.external_command_list)

Łukasz Nowak's avatar
Łukasz Nowak committed
444
class TestPartition(SlapformatMixin):
445 446

  def test_createPath(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
447 448
    global USER_LIST
    USER_LIST = ['testuser']
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    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
469
class TestUser(SlapformatMixin):
470
  def test_create(self):
471 472
    user = slapos.format.User('doesnotexistsyet')
    user.setPath('/doesnotexistsyet')
473 474
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
475 476 477
    self.assertEqual([
      'groupadd doesnotexistsyet',
      'useradd -d /doesnotexistsyet -g doesnotexistsyet -s /bin/false '\
478
        'doesnotexistsyet -r'
Łukasz Nowak's avatar
Łukasz Nowak committed
479
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
480
      self.fakeCallAndRead.external_command_list)
481 482

  def test_create_additional_groups(self):
483
    user = slapos.format.User('doesnotexistsyet', ['additionalgroup1',
484
      'additionalgroup2'])
485
    user.setPath('/doesnotexistsyet')
486 487
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
488 489 490
    self.assertEqual([
      'groupadd doesnotexistsyet',
      'useradd -d /doesnotexistsyet -g doesnotexistsyet -s /bin/false -G '\
491
        'additionalgroup1,additionalgroup2 doesnotexistsyet -r'
492
      ],
Łukasz Nowak's avatar
Łukasz Nowak committed
493
      self.fakeCallAndRead.external_command_list)
494 495

  def test_create_group_exists(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
496 497
    global GROUP_LIST
    GROUP_LIST = ['testuser']
498 499 500 501
    user = slapos.format.User('testuser')
    user.setPath('/testuser')
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
502
    self.assertEqual([
503
      'useradd -d /testuser -g testuser -s /bin/false testuser -r'
Łukasz Nowak's avatar
Łukasz Nowak committed
504
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
505
      self.fakeCallAndRead.external_command_list)
506 507

  def test_create_user_exists_additional_groups(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
508 509
    global USER_LIST
    USER_LIST = ['testuser']
510 511 512 513 514
    user = slapos.format.User('testuser', ['additionalgroup1',
      'additionalgroup2'])
    user.setPath('/testuser')
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
515 516 517 518 519
    self.assertEqual([
      'groupadd testuser',
      'usermod -d /testuser -g testuser -s /bin/false -G '\
        'additionalgroup1,additionalgroup2 testuser'
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
520
      self.fakeCallAndRead.external_command_list)
521 522

  def test_create_user_exists(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
523 524
    global USER_LIST
    USER_LIST = ['testuser']
525 526 527 528
    user = slapos.format.User('testuser')
    user.setPath('/testuser')
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
529 530 531 532
    self.assertEqual([
      'groupadd testuser',
      'usermod -d /testuser -g testuser -s /bin/false testuser'
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
533
      self.fakeCallAndRead.external_command_list)
534 535

  def test_create_user_group_exists(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
536 537 538 539
    global USER_LIST
    USER_LIST = ['testuser']
    global GROUP_LIST
    GROUP_LIST = ['testuser']
540 541 542 543
    user = slapos.format.User('testuser')
    user.setPath('/testuser')
    user.create()

Łukasz Nowak's avatar
Łukasz Nowak committed
544 545 546
    self.assertEqual([
      'usermod -d /testuser -g testuser -s /bin/false testuser'
    ],
Łukasz Nowak's avatar
Łukasz Nowak committed
547
      self.fakeCallAndRead.external_command_list)
548 549

  def test_isAvailable(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
550 551
    global USER_LIST
    USER_LIST = ['testuser']
552 553 554 555
    user = slapos.format.User('testuser')
    self.assertTrue(user.isAvailable())

  def test_isAvailable_notAvailable(self):
556
    user = slapos.format.User('doesnotexistsyet')
557 558 559 560
    self.assertFalse(user.isAvailable())

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