<commit_before># © 2015 Vauxoo
#   Coded by: <EMAIL>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import logging
import os
import subprocess
import time
import xmlrpc.client
import mock

from odoo.tests.common import TransactionCase
from odoo.exceptions import ValidationError, Warning as UserError
from odoo.tools.misc import mute_logger

_logger = logging.getLogger(__name__)


class TestRunbotJobs(TransactionCase):

    def setUp(self):
        super(TestRunbotJobs, self).setUp()
        self.build_obj = self.env['runbot.build']
        self.repo_obj = self.env['runbot.repo']
        self.branch_obj = self.env['runbot.branch']
        self.repo = self.repo_obj.search([
            ('is_travis2docker_build', '=', True)], limit=1)
        self.repo_domain = [('repo_id', '=', self.repo.id)]
        self.cron = self.env.ref('runbot.runbot_repo_cron')
        self.cron.write({'active': False})
        self.build = None

    def test_00_no_weblate_token(self):
        token = self.repo.weblate_token
        self.repo.weblate_token = None
        self.assertEqual(self.repo.weblate_validation(), None)
        with mute_logger('odoo.addons.runbot.models.repo'):
            self.assertEqual(self.repo.cron_weblate(), None)
        self.repo.weblate_token = token

    @mock.patch('requests.Session.get')
    def test_10_ok_weblate_validation(self, response):

        class Response(object):

            def raise_for_status(self):
                pass

            def json(self):
                return {'projects': []}

        response.return_value = Response()
        self.assertRaises(UserError, self.repo.weblate_validation)

    @mock.patch('requests.Session.get')
    def test_20_ko_weblate_validation(self, response):

        class Response(object):

            def raise_for_status(self):
                pass

            def json(self):
                return {}

        response.return_value = Response()
        self.assertRaises(ValidationError, self.repo.weblate_validation)

    def test_30_cron_weblate(self):
        with mute_logger('odoo.addons.runbot.models.repo'):
            self.assertEqual(self.repo.cron_weblate(), None)

    def tearDown(self):
        super(TestRunbotJobs, self).tearDown()
        if not self.build:
            return
        self.cron.write({'active': True})
        _logger.info('job_10_test_base log' +
                     open(os.path.join(self.build._path(), "logs",
                                       "job_10_test_base.txt")).read())
        _logger.info('job_20_test_all log' +
                     open(os.path.join(self.build._path(), "logs",
                                       "job_20_test_all.txt")).read())

    def wait_change_job(self, current_job, build,
                        loops=60, timeout=15):
        for loop in range(loops):
            _logger.info("Repo Cron to wait change of state")
            with mute_logger('odoo.addons.runbot.models.repo'):
                self.repo._cron()
            if build.job != current_job:
                break
            time.sleep(timeout)
        return build.job

    def test_jobs(self):
        'Create build and run all jobs'
        self.assertEqual(len(self.repo), 1, "Repo not found")
        _logger.info("Repo update to get branches")
        self.repo._update(self.repo)
        branch = self.branch_obj.search(self.repo_domain + [
            ('branch_name', '=', 'fast-travis-oca')], limit=1)
        if not branch:
            # If the branch has a commit too old then runbot ignore it
            branch = self.branch_obj.create({
                'repo_id': self.repo.id,
                'name': 'refs/heads/fast-travis-oca',
            })
        self.branch_obj.write({'uses_weblate', True})
        self.assertEqual(len(branch), 1, "Branch not found")
        self.build_obj.search([('branch_id', '=', branch.id)]).unlink()
        self.build_obj.create({'branch_id': branch.id, 'name': 'HEAD'})
        # runbot module has a inherit in create method
        # but a "return id" is missed. Then we need to search it.
        # https://github.com/odoo/odoo-extra/blob/038fd3e/runbot/runbot.py#L599
        self.build = self.build_obj.search([('branch_id', '=', branch.id)],
                                           limit=1)
        self.build.write({'uses_weblate': True})
        self.assertEqual(len(self.build) == 0, False, "Build not found")

        if self.build.state == 'done' and self.build.result == 'skipped':
            # When the last commit of the repo is too old,
            # runbot will skip this build then we are forcing it
            self.build._force()

        self.assertEqual(
            self.build.state, u'pending', "State should be pending")

        _logger.info("Repo Cron to change state to pending -> testing")
        with mute_logger('odoo.addons.runbot.models.repo'):
            self.repo._cron()
        self.assertEqual(
            self.build.state, u'testing', "State should be testing")
        self.assertEqual(
            self.build.job, u'job_10_test_base',
            "Job should be job_10_test_base")
        new_current_job = self.wait_change_job(self.build.job, self.build)

        self.assertEqual(
            new_current_job, u'job_20_test_all',
            "Job should be job_20_test_all")
        new_current_job = self.wait_change_job(new_current_job, self.build)

        self.assertEqual(<commit_msg>[REF] runbot_travis2docker: Comment uses of weblate because is down<commit_after># © 2015 Vauxoo
#   Coded by: <EMAIL>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import logging
import os
import subprocess
import time
import xmlrpc.client
import mock

from odoo.tests.common import TransactionCase
from odoo.exceptions import ValidationError, Warning as UserError
from odoo.tools.misc import mute_logger

_logger = logging.getLogger(__name__)


class TestRunbotJobs(TransactionCase):

    def setUp(self):
        super(TestRunbotJobs, self).setUp()
        self.build_obj = self.env['runbot.build']
        self.repo_obj = self.env['runbot.repo']
        self.branch_obj = self.env['runbot.branch']
        self.repo = self.repo_obj.search([
            ('is_travis2docker_build', '=', True)], limit=1)
        self.repo_domain = [('repo_id', '=', self.repo.id)]
        self.cron = self.env.ref('runbot.runbot_repo_cron')
        self.cron.write({'active': False})
        self.build = None

    def test_00_no_weblate_token(self):
        token = self.repo.weblate_token
        self.repo.weblate_token = None
        self.assertEqual(self.repo.weblate_validation(), None)
        with mute_logger('odoo.addons.runbot.models.repo'):
            self.assertEqual(self.repo.cron_weblate(), None)
        self.repo.weblate_token = token

    @mock.patch('requests.Session.get')
    def test_10_ok_weblate_validation(self, response):

        class Response(object):

            def raise_for_status(self):
                pass

            def json(self):
                return {'projects': []}

        response.return_value = Response()
        self.assertRaises(UserError, self.repo.weblate_validation)

    @mock.patch('requests.Session.get')
    def test_20_ko_weblate_validation(self, response):

        class Response(object):

            def raise_for_status(self):
                pass

            def json(self):
                return {}

        response.return_value = Response()
        self.assertRaises(ValidationError, self.repo.weblate_validation)

    def test_30_cron_weblate(self):
        with mute_logger('odoo.addons.runbot.models.repo'):
            self.assertEqual(self.repo.cron_weblate(), None)

    def tearDown(self):
        super(TestRunbotJobs, self).tearDown()
        if not self.build:
            return
        self.cron.write({'active': True})
        _logger.info('job_10_test_base log' +
                     open(os.path.join(self.build._path(), "logs",
                                       "job_10_test_base.txt")).read())
        _logger.info('job_20_test_all log' +
                     open(os.path.join(self.build._path(), "logs",
                                       "job_20_test_all.txt")).read())

    def wait_change_job(self, current_job, build,
                        loops=60, timeout=15):
        for loop in range(loops):
            _logger.info("Repo Cron to wait change of state")
            with mute_logger('odoo.addons.runbot.models.repo'):
                self.repo._cron()
            if build.job != current_job:
                break
            time.sleep(timeout)
        return build.job

    def test_jobs(self):
        'Create build and run all jobs'
        self.assertEqual(len(self.repo), 1, "Repo not found")
        _logger.info("Repo update to get branches")
        self.repo._update(self.repo)
        branch = self.branch_obj.search(self.repo_domain + [
            ('branch_name', '=', 'fast-travis-oca')], limit=1)
        if not branch:
            # If the branch has a commit too old then runbot ignore it
            branch = self.branch_obj.create({
                'repo_id': self.repo.id,
                'name': 'refs/heads/fast-travis-oca',
            })
        # self.branch_obj.write({'uses_weblate', True})  # Weblate is down :(
        self.assertEqual(len(branch), 1, "Branch not found")
        self.build_obj.search([('branch_id', '=', branch.id)]).unlink()
        self.build_obj.create({'branch_id': branch.id, 'name': 'HEAD'})
        # runbot module has a inherit in create method
        # but a "return id" is missed. Then we need to search it.
        # https://github.com/odoo/odoo-extra/blob/038fd3e/runbot/runbot.py#L599
        self.build = self.build_obj.search([('branch_id', '=', branch.id)],
                                           limit=1)
        # self.build.write({'uses_weblate': True})  # Weblate is down :(
        self.assertEqual(len(self.build) == 0, False, "Build not found")

        if self.build.state == 'done' and self.build.result == 'skipped':
            # When the last commit of the repo is too old,
            # runbot will skip this build then we are forcing it
            self.build._force()

        self.assertEqual(
            self.build.state, u'pending', "State should be pending")

        _logger.info("Repo Cron to change state to pending -> testing")
        with mute_logger('odoo.addons.runbot.models.repo'):
            self.repo._cron()
        self.assertEqual(
            self.build.state, u'testing', "State should be testing")
        self.assertEqual(
            self.build.job, u'job_10_test_base',
            "Job should be job_10_test_base")
        new_current_job = self.wait_change_job(self.build.job, self.build)

        self.assertEqual(
            new_current_job, u'job_20_test_all',
            "Job should be job_20_test_all")
        new_current_job = self.wait_change_job(new_current_job, self.build)

        self.assertEqual(
{'fraction_non_alphanumeric': 0.11888302710569401, 'fraction_numerical': 0.008822994360560306, 'mean_word_length': 2.2385861561119293, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3825648', 'n_tokens_mistral': 3443, 'n_tokens_neox': 3306, 'n_words': 675}