Example #1
0
    def run(self, args):

        # Loading instance
        M = self.Wp.resolve(args.name)
        if not M:
            raise Exception('This is not a Moodle instance')

        # Check if installed
        if not M.get('installed'):
            raise Exception('This instance needs to be installed first')

        # Check if testcase option is available.
        if args.testcase and M.branch_compare('26', '<'):
            self.argumentError('The --testcase option only works with Moodle 2.6 or greater.')

        # Composer was introduced with PHP Unit, if the JSON file is there then we will use it
        hasComposer = os.path.isfile(os.path.join(M.get('path'), 'composer.json'))

        # Install Composer
        if hasComposer:
            if not os.path.isfile(os.path.join(M.get('path'), 'composer.phar')):
                logging.info('Installing Composer')
                cliFile = 'phpunit_install_composer.php'
                cliPath = os.path.join(M.get('path'), 'phpunit_install_composer.php')
                (to, headers) = urllib.urlretrieve('http://getcomposer.org/installer', cliPath)
                if headers.dict.get('content-encoding') == 'gzip':
                    f = gzip.open(cliPath, 'r')
                    content = f.read()
                    f.close()
                    f = open(cliPath, 'w')
                    f.write(content)
                    f.close()
                M.cli('/' + cliFile, stdout=None, stderr=None)
                os.remove(cliPath)
                M.cli('composer.phar', args='install --dev', stdout=None, stderr=None)

        # Run cli
        try:
            M.initPHPUnit(force=args.force)
            logging.info('PHPUnit ready!')

            if args.unittest or args.testcase:
                args.run = True

            if args.run:
                cmd = []
                if hasComposer:
                    cmd.append('vendor/bin/phpunit')
                else:
                    cmd.append('phpunit')
                if args.testcase:
                    cmd.append(args.testcase)
                elif args.unittest:
                    cmd.append(args.unittest)
                cmd = ' '.join(cmd)
                process(cmd, M.get('path'), None, None)
        except Exception as e:
            raise e
Example #2
0
    def run(self, args):

        # Loading instance
        M = self.Wp.resolve(args.name)
        if not M:
            raise Exception('This is not a Moodle instance')

        # Check if installed
        if not M.get('installed'):
            raise Exception('This instance needs to be installed first')

        # Install Composer for >= 2.5
        if M.branch_compare(25):
            if not os.path.isfile(os.path.join(M.get('path'), 'composer.phar')):
                logging.info('Installing Composer')
                cliFile = 'phpunit_install_composer.php'
                cliPath = os.path.join(M.get('path'), 'phpunit_install_composer.php')
                (to, headers) = urllib.urlretrieve('http://getcomposer.org/installer', cliPath)
                if headers.dict.get('content-encoding') == 'gzip':
                    f = gzip.open(cliPath, 'r')
                    content = f.read()
                    f.close()
                    f = open(cliPath, 'w')
                    f.write(content)
                    f.close()
                M.cli('/' + cliFile, stdout=None, stderr=None)
                os.remove(cliPath)
                M.cli('composer.phar', args='install --dev', stdout=None, stderr=None)

        # Run cli
        try:
            M.initPHPUnit(force=args.force)
            logging.info('PHPUnit ready!')

            if args.unittest:
                args.run = True

            if args.run:
                cmd = []
                if M.branch_compare(25):
                    cmd.append('vendor/bin/phpunit')
                else:
                    cmd.append('phpunit')
                if args.unittest:
                    cmd.append(args.unittest)
                cmd = ' '.join(cmd)
                logging.info('Executing %s', cmd)
                process(cmd, M.get('path'), None, None)
        except Exception as e:
            raise e
Example #3
0
        parser.print_help()
    sys.exit(0)

# Looking up for an alias
alias = C.get('aliases.%s' % cmd)
if alias != None:
    if alias.startswith('!'):
        cmd = alias[1:]
        i = 0
        # Replace $1, $2, ... with passed arguments
        for arg in args:
            i += 1
            cmd = cmd.replace('$%d' % i, arg)
        # Remove unknown $[0-9]
        cmd = re.sub(r'\$[0-9]', '', cmd)
        result = process(cmd, stdout=None, stderr=None)
        sys.exit(result[0])
    else:
        cmd = alias.split(' ')[0]
        args = alias.split(' ')[1:] + args

cls = getCommand(cmd)
Cmd = cls(C)
Runner = CommandRunner(Cmd)
try:
    Runner.run(args, prog='%s %s' % (os.path.basename(sys.argv[0]), cmd))
except Exception as e:
    import traceback
    info = sys.exc_info()
    logging.error('%s: %s', e.__class__.__name__, e)
    logging.debug(''.join(traceback.format_tb(info[2])))
Example #4
0
    def run(self, args):

        # Loading instance
        M = self.Wp.resolve(args.name)
        if not M:
            raise Exception('This is not a Moodle instance')

        # Check required version
        if M.branch_compare(25, '<'):
            raise Exception('Behat is only available from Moodle 2.5')

        # Check if installed
        if not M.get('installed'):
            raise Exception('This instance needs to be installed first')

        # Disable Behat
        if args.disable and not args.run:
            self.disable(M)
            return

        # No Javascript
        nojavascript = args.nojavascript
        if not nojavascript and not self.C.get('java') or not os.path.isfile(os.path.abspath(self.C.get('java'))):
            nojavascript = True
            logging.info('Disabling Javascript because Java is required to run Selenium and could not be found.')

        # If not composer.phar, install Composer
        if not os.path.isfile(os.path.join(M.get('path'), 'composer.phar')):
            logging.info('Installing Composer')
            cliFile = 'behat_install_composer.php'
            cliPath = os.path.join(M.get('path'), 'behat_install_composer.php')
            (to, headers) = urllib.urlretrieve('http://getcomposer.org/installer', cliPath)
            if headers.dict.get('content-encoding') == 'gzip':
                f = gzip.open(cliPath, 'r')
                content = f.read()
                f.close()
                f = open(cliPath, 'w')
                f.write(content)
                f.close()
            M.cli('/' + cliFile, stdout=None, stderr=None)
            os.remove(cliPath)
            M.cli('composer.phar', args='install --dev', stdout=None, stderr=None)

        # Download selenium
        seleniumPath = os.path.expanduser(os.path.join(self.C.get('dirs.mdk'), 'selenium.jar'))
        if args.selenium:
            seleniumPath = args.selenium
        elif args.seleniumforcedl or (not nojavascript and not os.path.isfile(seleniumPath)):
            logging.info('Attempting to find a download for Selenium')
            url = urllib.urlopen('http://docs.seleniumhq.org/download/')
            content = url.read()
            selenium = re.search(r'http:[a-z0-9/._-]+selenium-server-standalone-[0-9.]+\.jar', content, re.I)
            if selenium:
                logging.info('Downloading Selenium from %s' % (selenium.group(0)))
                if (logging.getLogger().level <= logging.INFO):
                    urllib.urlretrieve(selenium.group(0), seleniumPath, downloadProcessHook)
                    # Force a new line after the hook display
                    logging.info('')
                else:
                    urllib.urlretrieve(selenium.group(0), seleniumPath)
            else:
                logging.warning('Could not locate Selenium server to download')

        if not nojavascript and not os.path.isfile(seleniumPath):
            raise Exception('Selenium file %s does not exist')

        # Run cli
        try:
            logging.info('Initialising Behat, please be patient!')
            M.initBehat(switchcompletely=args.switchcompletely)
            logging.info('Behat ready!')

            # Preparing Behat command
            cmd = ['vendor/bin/behat']
            if args.tags:
                cmd.append('--tags="%s"' % (args.tags))

            if args.testname:
                cmd.append('--name="%s"' % (args.testname))

            if not (args.tags or args.testname or args.feature) and nojavascript:
                cmd.append('--tags ~@javascript')

            if (args.stoponfailure):
                cmd.append('--stop-on-failure')

            if (args.profile):
                cmd.append('-p %s' % (args.profile))

            cmd.append('--config=%s/behat/behat.yml' % (M.get('behat_dataroot')))

            # Checking feature argument
            if args.feature:
                filepath = args.feature
                if not filepath.startswith('/'):
                    filepath = os.path.join(M.get('path'), filepath)
                cmd.append(filepath)

            cmd = ' '.join(cmd)

            phpCommand = '%s -S localhost:8000' % (self.C.get('php'))
            seleniumCommand = None
            if seleniumPath:
                seleniumCommand = '%s -jar %s' % (self.C.get('java'), seleniumPath)

            if args.run:
                logging.info('Preparing Behat testing')

                # Preparing PHP Server
                phpServer = None
                if not M.get('behat_switchcompletely'):
                    logging.info('Starting standalone PHP server')
                    kwargs = {}
                    kwargs['cwd'] = M.get('path')
                    phpServer = ProcessInThread(phpCommand, **kwargs)
                    phpServer.start()

                # Launching Selenium
                seleniumServer = None
                if seleniumPath and not nojavascript:
                    logging.info('Starting Selenium server')
                    kwargs = {}
                    if args.seleniumverbose:
                        kwargs['stdout'] = None
                        kwargs['stderr'] = None
                    seleniumServer = ProcessInThread(seleniumCommand, **kwargs)
                    seleniumServer.start()

                logging.info('Running Behat tests')

                # Sleep for a few seconds before starting Behat
                if phpServer or seleniumServer:
                    sleep(3)

                # Running the tests
                (returncode, none, none) = process(cmd, M.path, None, None)
                if (args.stoponfailure):
                    sys.exit(returncode)

                # Kill the remaining processes
                if phpServer:
                    phpServer.kill()
                if seleniumServer:
                    seleniumServer.kill()

                # Disable Behat
                if args.disable:
                    self.disable(M)

            else:
                if M.branch_compare(27, '<'):
                    logging.info('Launch PHP Server (or set $CFG->behat_switchcompletely to True):\n %s' % (phpCommand))
                if seleniumCommand:
                    logging.info('Launch Selenium (optional):\n %s' % (seleniumCommand))
                logging.info('Launch Behat:\n %s' % (cmd))

        except Exception as e:
            raise e
Example #5
0
# Arguments
parser = argparse.ArgumentParser(description='Initialize PHPUnit')
parser.add_argument('-f', '--force', action='store_true', help='force the initialisation')
parser.add_argument('-r', '--run', action='store_true', help='also run the tests')
parser.add_argument('name', metavar='name', default=None, nargs='?', help='name of the instance')
args = parser.parse_args()

Wp = workplace.Workplace(C.get('dirs.storage'))

# Loading instance
M = Wp.resolve(args.name)
if not M:
    debug('This is not a Moodle instance')
    sys.exit(1)

# Check if installed
if not M.get('installed'):
    debug('This instance needs to be installed first')
    sys.exit(1)

# Run cli
try:
    M.initPHPUnit(force=args.force)
    debug('PHPUnit ready!')
    if args.run:
        debug('Running PHPUnit')
        process('phpunit', M.path, None, None)
except Exception as e:
    debug(e)
    sys.exit(1)
Example #6
0
parser.add_argument('name',
                    metavar='name',
                    default=None,
                    nargs='?',
                    help='name of the instance')
args = parser.parse_args()

Wp = workplace.Workplace(C.get('dirs.storage'))

# Loading instance
M = Wp.resolve(args.name)
if not M:
    debug('This is not a Moodle instance')
    sys.exit(1)

# Check if installed
if not M.get('installed'):
    debug('This instance needs to be installed first')
    sys.exit(1)

# Run cli
try:
    M.initPHPUnit(force=args.force)
    debug('PHPUnit ready!')
    if args.run:
        debug('Running PHPUnit')
        process('phpunit', M.path, None, None)
except Exception as e:
    debug(e)
    sys.exit(1)
Example #7
0
            debug("Starting Selenium server")
            kwargs = {}
            if args.seleniumverbose:
                kwargs["stdout"] = None
                kwargs["stderr"] = None
            seleniumServer = ProcessInThread(seleniumCommand, **kwargs)
            seleniumServer.start()

        debug("Running Behat tests")

        # Sleep for a few seconds before starting Behat
        if phpServer or seleniumServer:
            sleep(3)

        # Running the tests
        process(cmd, M.path, None, None)

        # Kill the remaining processes
        if phpServer:
            phpServer.kill()
        if seleniumServer:
            seleniumServer.kill()

        # Remove the switch completely tag
        if M.get("behat_switchcompletely"):
            M.removeConfig("behat_switchcompletely")

    else:
        debug("Launch PHP Server (or set $CFG->behat_switchcompletely to True):\n %s" % (phpCommand))
        if seleniumCommand:
            debug("Launch Selenium (optional):\n %s" % (seleniumCommand))
Example #8
0
            debug('Starting Selenium server')
            kwargs = {}
            if args.seleniumverbose:
                kwargs['stdout'] = None
                kwargs['stderr'] = None
            seleniumServer = ProcessInThread(seleniumCommand, **kwargs)
            seleniumServer.start()

        debug('Running Behat tests')

        # Sleep for a few seconds before starting Behat
        if phpServer or seleniumServer:
            sleep(3)

        # Running the tests
        process(cmd, M.path, None, None)

        # Kill the remaining processes
        if phpServer:
            phpServer.kill()
        if seleniumServer:
            seleniumServer.kill()

        # Remove the switch completely tag
        if M.get('behat_switchcompletely'):
            M.removeConfig('behat_switchcompletely')

    else:
        debug(
            'Launch PHP Server (or set $CFG->behat_switchcompletely to True):\n %s'
            % (phpCommand))