test_runner.py 13.2 KB
Newer Older
1
import mock
2 3 4
import os
import string
import random
5 6
import supervisor
import thread
7 8
import unittest

9 10 11 12 13 14

import slapos.runner.utils as runner_utils

import sys
sys.modules['slapos.runner.utils'].sup_process = mock.MagicMock()

15

16
class TestRunnerBackEnd(unittest.TestCase):
17 18 19
  def setUp(self):
    self.sup_process = runner_utils.sup_process
    self.sup_process.reset_mock()
20
    runner_utils.open = open
21

22
  def tearDown(self):
23 24 25 26 27 28 29 30
    garbage_file_list = [
      os.path.join(*(os.getcwd(), '.htpasswd')),
      os.path.join(*(os.getcwd(), '.turn-left')),
      os.path.join(*(os.getcwd(), 'slapos-test.cfg')),
    ]
    for garbage_file in garbage_file_list:
      if os.path.exists(garbage_file):
        os.remove(garbage_file)
31

32 33 34 35 36 37 38 39
  def _startSupervisord(self):
    cwd = os.getcwd()
    supervisord_config_file = os.path.join(cwd, 'supervisord.conf')
    open(supervisord_config_file, 'w').write("""
    """)
    supervisord = supervisor.supervisord.Supervisord('-c', supervisord_config_file)
    thread.start_new_thread()

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  def test_UserCanLoginAndUpdateCredentials(self):
    """
    * Create a user with createNewUser
    * Tests user can login with checkUserCredential
    * Updates user password updateUserCredential
    * Checks user can login with new credentials
    """
    def generate_password():
      return "".join(random.sample( \
        string.ascii_letters + string.digits + string.punctuation, 20))

    config = {'etc_dir': os.getcwd()}
    login = "admin"
    password = generate_password()
    self.assertTrue(runner_utils.createNewUser(config, login, password))
    self.assertTrue(runner_utils.checkUserCredential(config, login, password))

    new_password = generate_password()
    self.assertNotEqual(password, new_password)
    runner_utils.updateUserCredential(config, login, new_password)
    self.assertTrue(runner_utils.checkUserCredential(config, login, new_password))

62
  @mock.patch('os.path.exists')
63
  def test_getCurrentSoftwareReleaseProfile(self, mock_path_exists):
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    """
    * Mock a .project file
    * Tests that getCurrentSoftwareReleaseProfile returns an absolute path
    """
    cwd = os.getcwd()

    # If .project file doesn't exist, then getCurrentSoftwareReleaseProfile
    # returns an empty string
    config = {'etc_dir': os.path.join(cwd, 'etc'),
              'workspace': os.path.join(cwd, 'srv', 'runner'),
              'software_profile': 'software.cfg'}

    profile = runner_utils.getCurrentSoftwareReleaseProfile(config)
    self.assertEqual(profile, "")

    # If .project points to a SR that doesn't exist, returns empty string
80
    runner_utils.open = mock.mock_open(read_data="workspace/fake/path/")
81 82 83 84 85 86
    mock_path_exists.return_value = False
    profile = runner_utils.getCurrentSoftwareReleaseProfile(config)
    self.assertEqual(profile, "")

    # If software_profile exists, getCurrentSoftwareReleaseProfile should
    # return its absolute path
87
    runner_utils.open = mock.mock_open(read_data = "workspace/project/software/")
88 89 90 91 92
    mock_path_exists.return_value = True
    profile = runner_utils.getCurrentSoftwareReleaseProfile(config)
    self.assertEqual(profile, os.path.join(config['workspace'], 'project',
        'software', config['software_profile']))

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
  @mock.patch('os.mkdir')
  @mock.patch('slapos.runner.utils.updateProxy')
  @mock.patch('slapos.runner.utils.config_SR_folder')
  def _runSlapgridWithLockMakesCorrectCallsToSupervisord(self,
                                                         run_slapgrid_function,
                                                         process_name,
                                                         mock_configSRFolder,
                                                         mock_updateProxy,
                                                         mock_mkdir):
    """
    Tests that runSoftwareWithLock and runInstanceWithLock make correct calls
    to sup_process (= supervisord)
    """
    mock_updateProxy.return_value = True
    cwd = os.getcwd()
    config = {'software_root': os.path.join(cwd, 'software'),
              'software_log': os.path.join(cwd, 'software.log'),
              'instance_root': os.path.join(cwd, 'software'),
              'instance_log': os.path.join(cwd, 'software.log')}
    # If process is already running, then does nothing
113
    self.sup_process.isRunning.return_value = True
114
    self.assertEqual(run_slapgrid_function(config), 1)
115
    self.assertFalse(self.sup_process.runProcess.called)
116 117

    # If the slapgrid process is not running, it should start it
118
    self.sup_process.isRunning.return_value = False
119 120
    # First, without Lock
    run_slapgrid_function(config)
121 122
    self.sup_process.runProcess.assert_called_once_with(config, process_name)
    self.assertFalse(self.sup_process.waitForProcessEnd.called)
123
    # Second, with Lock
124
    self.sup_process.reset_mock()
125
    run_slapgrid_function(config, lock=True)
126 127
    self.sup_process.runProcess.assert_called_once_with(config, process_name)
    self.sup_process.waitForProcessEnd.assert_called_once_with(config, process_name)
128 129 130 131 132 133 134 135 136

  def test_runSoftwareWithLockMakesCorrectCallstoSupervisord(self):
    self._runSlapgridWithLockMakesCorrectCallsToSupervisord(
      runner_utils.runSoftwareWithLock, 'slapgrid-sr')

  def test_runInstanceWithLockMakesCorrectCallstoSupervisord(self):
    self._runSlapgridWithLockMakesCorrectCallsToSupervisord(
      runner_utils.runInstanceWithLock, 'slapgrid-cp')

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  @mock.patch('os.path.exists')
  @mock.patch('os.remove')
  @mock.patch('slapos.runner.utils.startProxy')
  @mock.patch('slapos.runner.utils.stopProxy')
  @mock.patch('slapos.runner.utils.removeProxyDb')
  def test_changingSRUpdatesProjectFileWithExistingPath(self,
                                                        mock_removeProxyDb,
                                                        mock_stopProxy,
                                                        mock_startProxy,
                                                        mock_remove,
                                                        mock_path_exists):
    cwd = os.getcwd()
    config = {'etc_dir' : os.path.join(cwd, 'etc'),
              'workspace': os.path.join(cwd, 'srv', 'runner')}
    projectpath = 'workspace/project/software/'
    self.assertNotEqual(runner_utils.realpath(config, projectpath, \
                                              check_exist=False), '')

    # If projectpath doesn't exist, .project file shouldn't be written
    mock_path_exists.return_value = False
    result = runner_utils.configNewSR(config, projectpath)
    self.assertFalse(result)

    # If projectpath exist, .project file should be overwritten
    mock_path_exists.return_value = True
162
    runner_utils.open = mock.mock_open()
163 164
    result = runner_utils.configNewSR(config, projectpath)
    self.assertTrue(result)
165
    runner_utils.open.assert_has_calls([mock.call().write(projectpath)])
166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  @mock.patch('slapos.runner.utils.isInstanceRunning')
  @mock.patch('slapos.runner.utils.svcStopAll')
  def test_removingInstanceStopsProcessesAndCleansInstanceDirectory(self,
                                                                    mock_svcStopAll,
                                                                    mock_isInstanceRunning):
    """
    When removing the current running instances, processes should be stopped
    and directories deleted properly
    """
    cwd = os.getcwd()
    config = {'database_uri': os.path.join(cwd, 'proxy.db'),
              'etc_dir': os.path.join(cwd, 'etc'),
              'instance_root': os.path.join(cwd, 'instance'),}

    # If slapos node is running, removeCurrentInstance returns a string
    mock_isInstanceRunning.return_value = True
    self.assertTrue(isinstance(runner_utils.removeCurrentInstance(config), str))
    self.assertTrue(mock_isInstanceRunning.called)

    # If slapos is not running, process should be stopped and directories emptied
    mock_isInstanceRunning.return_value = False
    result = runner_utils.removeCurrentInstance(config)
    self.assertTrue(mock_svcStopAll.called)
    self.sup_process.stopProcess.assert_called_with(config, 'slapproxy')
191

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
  @mock.patch('os.listdir')
  @mock.patch('os.path.exists')
  @mock.patch('slapos.runner.utils.removeCurrentInstance')
  @mock.patch('slapos.runner.utils.removeSoftwareRootDirectory')
  def test_removingUsedSoftwareReleaseCleansInstancesToo(self,
                                                         mock_removeSoftwareRootDirectory,
                                                         mock_removeCurrentInstance,
                                                         mock_path_exists,
                                                         mock_listdir):
    """
    When removing the Software Release on which depends the current running
    instances, the current instances should be stopped and removed properly.
    """
    # mock_listir is needed for not raising in loadSoftwareRList or future equivalent
    mock_listdir.return_value = []

    cwd = os.getcwd()
    config = {'etc_dir': os.path.join(cwd, 'etc'),
              'software_root': os.path.join(cwd, 'software'),
              'software_link': os.path.join(cwd, 'softwareLink'),}

    self.sup_process.isRunning.return_value = False

    # First tests that if the current instance doesn't extend the Software
    # Release to delete, the instance isn't deleted
    runner_utils.open = mock.mock_open(read_data="/workspace/software/another/")
    runner_utils.removeSoftwareByName(config, '1234567890', 'my_software_name')

    self.assertFalse(mock_removeCurrentInstance.called)
    self.assertTrue(mock_removeSoftwareRootDirectory.called)

    # If the current Instance extends the Software Release, then both must
    # be removed
    mock_removeSoftwareRootDirectory.reset_mock()

    runner_utils.open = mock.mock_open(read_data="/workspace/software/my_software_name/")
    runner_utils.removeSoftwareByName(config, '1234567890', 'my_software_name')

    self.assertTrue(mock_removeCurrentInstance.called)
    self.assertTrue(mock_removeSoftwareRootDirectory.called)

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  @mock.patch('slapos.runner.utils.runInstanceWithLock')
  @mock.patch('slapos.runner.utils.runSoftwareWithLock')
  def test_runSoftwareRunOnlyOnceIfSoftwareSuccessfullyCompiledOnFirstTime(self,
                                                                           mock_runSoftwareWithLock,
                                                                           mock_runInstanceWithLock):
    cwd = os.getcwd()
    config = {'runner_workdir': cwd,
              'etc_dir': cwd}

    build_and_run_parameter_dict = {
      'run_instance': False,
      'run_software': True,
      'max_run_instance': 3,
      'max_run_software': 3,
    }
    runner_utils.saveBuildAndRunParams(config, build_and_run_parameter_dict)

    # First, configuration is set to only run the compilation of the software release
    # Both runSoftwareWithLock and runInstanceWithLock succeed on 1st try
    mock_runSoftwareWithLock.return_value = 0
    mock_runInstanceWithLock.return_value = 0

    runner_utils.runSlapgridUntilSuccess(config, 'software')
    self.assertEqual(mock_runSoftwareWithLock.call_count, 1)
    self.assertEqual(mock_runInstanceWithLock.call_count, 0)

    # Second, instanciation should start if compilation succeeded
    mock_runSoftwareWithLock.reset_mock()
    build_and_run_parameter_dict.update({'run_instance': True})
    runner_utils.saveBuildAndRunParams(config, build_and_run_parameter_dict)

    runner_utils.runSlapgridUntilSuccess(config, 'software')
    self.assertEqual(mock_runSoftwareWithLock.call_count, 1)
    self.assertEqual(mock_runInstanceWithLock.call_count, 1)

  @mock.patch('slapos.runner.utils.runInstanceWithLock')
  @mock.patch('slapos.runner.utils.runSoftwareWithLock')
  def test_runSoftwareDonotRestartForeverEvenIfBuildoutFileIsWrong(self,
                                                                   mock_runSoftwareWithLock,
                                                                   mock_runInstanceWithLock):
    """
    Restarting compilation or instanciation should happen a limited number of
    times to prevent useless runs due to a mistaken buildout config.
    """
    cwd = os.getcwd()
    config = {'runner_workdir': cwd,
              'etc_dir': cwd}

    build_and_run_parameter_dict = {
      'run_instance': True,
      'run_software': True,
      'max_run_instance': 3,
      'max_run_software': 3,
    }
    runner_utils.saveBuildAndRunParams(config, build_and_run_parameter_dict)

    # runSoftwareWithLock always fail and runInstanceWithLock succeeds on 1st try
    mock_runSoftwareWithLock.return_value = 1
    mock_runInstanceWithLock.return_value = 0

    runner_utils.runSlapgridUntilSuccess(config, 'software')
    self.assertEqual(mock_runSoftwareWithLock.call_count,
                     build_and_run_parameter_dict['max_run_software'])
    # if running software fails, then no need to try to deploy instances
    self.assertEqual(mock_runInstanceWithLock.call_count, 0)
298

299 300 301 302 303 304 305 306 307 308 309 310 311
  @unittest.skip('No scenario defined')
  def test_autoDeployWontEraseExistingInstances(self):
    raise NotImplementedError

  @unittest.skip('No scenario defined')
  def test_requestingInstanceCorrectlyPassesTypeAndParameters(self):
    raise NotImplementedError

  @unittest.skip('No scenario defined')
  def test_parametersAreCorrectlyUpdatedAndGivenToTheInstance(self):
    raise NotImplementedError


312 313 314
if __name__ == '__main__':
  random.seed()
  unittest.main()