Beispiel #1
0
    def test_ordered_search_same_timestamp(self):
        'Test ordered search  with same timestamp'
        pool = Pool()
        History = pool.get('test.history')
        transaction = Transaction()
        order = [('value', 'ASC')]

        history = History(value=1)
        history.save()
        first_stamp = history.create_date
        history.value = 4
        history.save()
        second_stamp = history.write_date

        self.assertEqual(first_stamp, second_stamp)
        transaction.commit()

        results = [
            (second_stamp, [history], [4]),
            (datetime.datetime.now(), [history], [4]),
            (datetime.datetime.max, [history], [4]),
            ]

        for timestamp, instances, values in results:
            with Transaction().set_context(_datetime=timestamp,
                    last_test=True):
                records = History.search([], order=order)
                self.assertEqual(records, instances)
                self.assertEqual([x.value for x in records], values)
            transaction.rollback()
Beispiel #2
0
    def test_integer_required(self):
        'Test required integer'
        pool = Pool()
        IntegerRequired = pool.get('test.import_data.integer_required')
        transaction = Transaction()

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['1']]), 1)

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['-1']]), 1)

        self.assertRaises(UserError, IntegerRequired.import_data,
            ['integer'], [['']])
        transaction.rollback()

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['1'], ['2']]), 2)

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['1.1']])

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['-1.1']])

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['foo']])

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['0']]), 1)
Beispiel #3
0
    def test_numeric_required(self):
        'Test required numeric'
        pool = Pool()
        NumericRequired = pool.get('test.import_data.numeric_required')
        transaction = Transaction()

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1.1']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['-1.1']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1']]), 1)

        self.assertRaises(UserError, NumericRequired.import_data,
            ['numeric'], [['']])
        transaction.rollback()

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(InvalidOperation,
            NumericRequired.import_data, ['numeric'], [['foo']])

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['0']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['0.0']]), 1)
Beispiel #4
0
    def test_SMTPDataManager(self, get_smtp_server):
        "Test SMTPDataManager"
        transaction = Transaction()
        get_smtp_server.return_value = server = Mock()

        datamanager = transaction.join(SMTPDataManager())

        # multiple join must return the same
        self.assertEqual(transaction.join(SMTPDataManager()), datamanager)

        msg1 = Mock(Message)
        msg2 = Mock(Message)
        datamanager.put("*****@*****.**", "*****@*****.**", msg1)
        datamanager.put("*****@*****.**", "*****@*****.**", msg2)

        transaction.commit()

        server.sendmail.assert_has_calls(
            [
                call("*****@*****.**", "*****@*****.**", msg1.as_string()),
                call("*****@*****.**", "*****@*****.**", msg2.as_string()),
            ]
        )
        server.quit.assert_called_once_with()
        self.assertFalse(datamanager.queue)

        server.reset_mock()

        datamanager.put("*****@*****.**", "*****@*****.**", Mock(Message))
        transaction.rollback()

        server.sendmail.assert_not_called()
        self.assertFalse(datamanager.queue)
Beispiel #5
0
    def test_float_required(self):
        'Test required float'
        pool = Pool()
        FloatRequired = pool.get('test.import_data.float_required')
        transaction = Transaction()

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1.1']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['-1.1']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1']]), 1)

        self.assertRaises(UserError, FloatRequired.import_data,
            ['float'], [['']])
        transaction.rollback()

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(ValueError, FloatRequired.import_data,
            ['float'], [['foo']])

        self.assertEqual(FloatRequired.import_data(['float'],
            [['0']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['0.0']]), 1)
Beispiel #6
0
 def wrapper(*args, **kwargs):
     transaction = Transaction()
     with transaction.start(DB_NAME, user, context=context):
         result = func(*args, **kwargs)
         transaction.rollback()
         # Drop the cache as the transaction is rollbacked
         Cache.drop(DB_NAME)
         return result
Beispiel #7
0
 def wrapper(*args, **kwargs):
     transaction = Transaction()
     with transaction.start(DB_NAME, user, context=context):
         result = func(*args, **kwargs)
         transaction.rollback()
         # Drop the cache as the transaction is rollbacked
         Cache.drop(DB_NAME)
         return result
Beispiel #8
0
def post_import(pool, module, to_delete):
    """
    Remove the records that are given in to_delete.
    """
    transaction = Transaction()
    mdata_delete = []
    ModelData = pool.get("ir.model.data")

    with Transaction().set_context(active_test=False):
        mdata = ModelData.search([
            ('fs_id', 'in', to_delete),
            ('module', '=', module),
            ], order=[('id', 'DESC')])

    for mrec in mdata:
        model, db_id, fs_id = mrec.model, mrec.db_id, mrec.fs_id

        logger.info('Deleting %s@%s from %s.%s', db_id, model, module, fs_id)
        try:
            # Deletion of the record
            try:
                Model = pool.get(model)
            except KeyError:
                Model = None
            if Model:
                Model.delete([Model(db_id)])
                mdata_delete.append(mrec)
            else:
                logger.warning(
                    'Could not delete id %d of model %s because model no '
                    'longer exists.', db_id, model)
        except Exception:
            transaction.rollback()
            logger.error(
                "Could not delete id %d from model %s.\n"
                "There may be a relation that points to this resource "
                "that must be manually fixed before restarting the update.",
                db_id, model, exc_info=True)
            if 'active' in Model._fields:
                try:
                    Model.write([Model(db_id)], {
                            'active': False,
                            })
                except Exception:
                    transaction.rollback()
                    logger.error(
                        'Could not inactivate id: %d of model %s\n',
                        db_id, model, exc_info=True)
        transaction.commit()

    # Clean model_data:
    if mdata_delete:
        ModelData.delete(mdata_delete)
        transaction.commit()

    return True
    def test_MessageDataManager_rollback(self, get_twilio_client, sendmessage):
        "Test MessageDataManager rollback"
        transaction = Transaction()

        datamanager = transaction.join(twilio_messages.MessageDataManager())
        message = {}
        datamanager.put(message)
        transaction.rollback()

        sendmessage.assert_not_called()
        self.assertFalse(datamanager.queue)
Beispiel #10
0
    def _load_modules():
        global res
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().cursor

        # Migration from 3.6: remove double module
        old_table = 'ir_module_module'
        new_table = 'ir_module'
        if TableHandler.table_exist(cursor, old_table):
            TableHandler.table_rename(cursor, old_table, new_table)
        if update:
            cursor.execute(*ir_module.select(ir_module.name,
                    where=ir_module.state.in_(('installed', 'to install',
                            'to upgrade', 'to remove'))))
        else:
            cursor.execute(*ir_module.select(ir_module.name,
                    where=ir_module.state.in_(('installed', 'to upgrade',
                            'to remove'))))
        module_list = [name for (name,) in cursor.fetchall()]
        if update:
            module_list += update
        graph = create_graph(module_list)[0]

        try:
            load_module_graph(graph, pool, update, lang)
        except Exception:
            cursor.rollback()
            raise

        if update:
            cursor.execute(*ir_module.select(ir_module.name,
                    where=(ir_module.state == 'to remove')))
            fetchall = cursor.fetchall()
            if fetchall:
                for (mod_name,) in fetchall:
                    # TODO check if ressource not updated by the user
                    cursor.execute(*ir_model_data.select(ir_model_data.model,
                            ir_model_data.db_id,
                            where=(ir_model_data.module == mod_name),
                            order_by=ir_model_data.id.desc))
                    for rmod, rid in cursor.fetchall():
                        Model = pool.get(rmod)
                        Model.delete([Model(rid)])
                    cursor.commit()
                cursor.execute(*ir_module.update([ir_module.state],
                        ['uninstalled'],
                        where=(ir_module.state == 'to remove')))
                cursor.commit()
                res = False

            Module = pool.get('ir.module')
            Module.update_list()
        cursor.commit()
        Cache.resets(database_name)
Beispiel #11
0
    def _load_modules():
        global res
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().cursor

        # Migration from 3.6: remove double module
        old_table = 'ir_module_module'
        new_table = 'ir_module'
        if TableHandler.table_exist(cursor, old_table):
            TableHandler.table_rename(cursor, old_table, new_table)
        if update:
            cursor.execute(*ir_module.select(ir_module.name,
                    where=ir_module.state.in_(('installed', 'to install',
                            'to upgrade', 'to remove'))))
        else:
            cursor.execute(*ir_module.select(ir_module.name,
                    where=ir_module.state.in_(('installed', 'to upgrade',
                            'to remove'))))
        module_list = [name for (name,) in cursor.fetchall()]
        if update:
            module_list += update
        graph = create_graph(module_list)[0]

        try:
            load_module_graph(graph, pool, update, lang)
        except Exception:
            cursor.rollback()
            raise

        if update:
            cursor.execute(*ir_module.select(ir_module.name,
                    where=(ir_module.state == 'to remove')))
            fetchall = cursor.fetchall()
            if fetchall:
                for (mod_name,) in fetchall:
                    # TODO check if ressource not updated by the user
                    cursor.execute(*ir_model_data.select(ir_model_data.model,
                            ir_model_data.db_id,
                            where=(ir_model_data.module == mod_name),
                            order_by=ir_model_data.id.desc))
                    for rmod, rid in cursor.fetchall():
                        Model = pool.get(rmod)
                        Model.delete([Model(rid)])
                    cursor.commit()
                cursor.execute(*ir_module.update([ir_module.state],
                        ['uninstalled'],
                        where=(ir_module.state == 'to remove')))
                cursor.commit()
                res = False

            Module = pool.get('ir.module')
            Module.update_list()
        cursor.commit()
        Cache.resets(database_name)
Beispiel #12
0
def post_import(pool, module, to_delete):
    """
    Remove the records that are given in to_delete.
    """
    cursor = Transaction().cursor
    mdata_delete = []
    ModelData = pool.get("ir.model.data")

    with Transaction().set_context(active_test=False):
        mdata = ModelData.search([
            ('fs_id', 'in', to_delete),
            ('module', '=', module),
            ], order=[('id', 'DESC')])

    object_name_list = set(pool.object_name_list())
    for mrec in mdata:
        model, db_id = mrec.model, mrec.db_id

        logging.getLogger("convert").info(
                'Deleting %s@%s' % (db_id, model))
        try:
            # Deletion of the record
            if model in object_name_list:
                Model = pool.get(model)
                Model.delete([Model(db_id)])
                mdata_delete.append(mrec)
            else:
                logging.getLogger("convert").warning(
                        'Could not delete id %d of model %s because model no '
                        'longer exists.' % (db_id, model))
            cursor.commit()
        except Exception:
            cursor.rollback()
            tb_s = ''.join(traceback.format_exception(*sys.exc_info()))
            logging.getLogger("convert").error(
                'Could not delete id: %d of model %s\n'
                    'There should be some relation '
                    'that points to this resource\n'
                    'You should manually fix this '
                    'and restart --update=module\n'
                    'Exception: %s' %
                    (db_id, model, tb_s))
            if 'active' in Model._fields:
                Model.write([Model(db_id)], {
                        'active': False,
                        })

    # Clean model_data:
    if mdata_delete:
        ModelData.delete(mdata_delete)
        cursor.commit()

    return True
Beispiel #13
0
    def test_many2one(self):
        'Test many2one'
        pool = Pool()
        Many2one = pool.get('test.import_data.many2one')
        transaction = Transaction()

        self.assertEqual(Many2one.import_data(['many2one'],
            [['Test']]), 1)

        self.assertEqual(Many2one.import_data(['many2one:id'],
            [['tests.import_data_many2one_target_test']]), 1)

        self.assertEqual(Many2one.import_data(['many2one'],
            [['']]), 1)

        self.assertEqual(Many2one.import_data(['many2one'],
            [['Test'], ['Test']]), 2)

        self.assertRaises(UserError, Many2one.import_data,
            ['many2one'], [['foo']])
        transaction.rollback()

        self.assertRaises(UserError, Many2one.import_data,
            ['many2one'], [['Duplicate']])
        transaction.rollback()

        self.assertRaises(UserError, Many2one.import_data,
            ['many2one:id'], [['foo']])
        transaction.rollback()

        self.assertRaises(Exception, Many2one.import_data,
            ['many2one:id'], [['tests.foo']])
        transaction.rollback()
    def test_many2one(self):
        'Test many2one'
        pool = Pool()
        Many2one = pool.get('test.import_data.many2one')
        transaction = Transaction()

        self.assertEqual(Many2one.import_data(['many2one'], [['Test']]), 1)

        self.assertEqual(
            Many2one.import_data(['many2one:id'],
                                 [['tests.import_data_many2one_target_test']]),
            1)

        self.assertEqual(Many2one.import_data(['many2one'], [['']]), 1)

        self.assertEqual(
            Many2one.import_data(['many2one'], [['Test'], ['Test']]), 2)

        self.assertRaises(UserError, Many2one.import_data, ['many2one'],
                          [['foo']])
        transaction.rollback()

        self.assertRaises(UserError, Many2one.import_data, ['many2one'],
                          [['Duplicate']])
        transaction.rollback()

        self.assertRaises(UserError, Many2one.import_data, ['many2one:id'],
                          [['foo']])
        transaction.rollback()

        self.assertRaises(Exception, Many2one.import_data, ['many2one:id'],
                          [['tests.foo']])
        transaction.rollback()
Beispiel #15
0
    def test_phone_number_format(self):
        'Test phone number format'
        pool = Pool()
        Party = pool.get('party.party')
        ContactMechanism = pool.get('party.contact_mechanism')
        transaction = Transaction()

        def create(mtype, mvalue):
            party1, = Party.create([{
                'name': 'Party 1',
            }])
            return ContactMechanism.create([{
                'party': party1.id,
                'type': mtype,
                'value': mvalue,
            }])[0]

        # Test format on create
        mechanism = create('phone', '+442083661177')
        self.assertEqual(mechanism.value, '+44 20 8366 1177')
        self.assertEqual(mechanism.value_compact, '+442083661177')

        # Test format on write
        mechanism.value = '+442083661178'
        mechanism.save()
        self.assertEqual(mechanism.value, '+44 20 8366 1178')
        self.assertEqual(mechanism.value_compact, '+442083661178')

        ContactMechanism.write([mechanism], {
            'value': '+442083661179',
        })
        self.assertEqual(mechanism.value, '+44 20 8366 1179')
        self.assertEqual(mechanism.value_compact, '+442083661179')

        # Test rejection of a phone type mechanism to non-phone value
        with self.assertRaises(UserError):
            mechanism.value = '*****@*****.**'
            mechanism.save()
        transaction.rollback()

        # Test rejection of invalid phone number creation
        with self.assertRaises(UserError):
            mechanism = create('phone', '*****@*****.**')
        transaction.rollback()

        # Test acceptance of a non-phone value when type is non-phone
        mechanism = create('email', '*****@*****.**')
Beispiel #16
0
    def test_phone_number_format(self):
        'Test phone number format'
        pool = Pool()
        Party = pool.get('party.party')
        ContactMechanism = pool.get('party.contact_mechanism')
        transaction = Transaction()

        def create(mtype, mvalue):
            party1, = Party.create([{
                        'name': 'Party 1',
                        }])
            return ContactMechanism.create([{
                        'party': party1.id,
                        'type': mtype,
                        'value': mvalue,
                        }])[0]

        # Test format on create
        mechanism = create('phone', '+442083661177')
        self.assertEqual(mechanism.value, '+44 20 8366 1177')
        self.assertEqual(mechanism.value_compact, '+442083661177')

        # Test format on write
        mechanism.value = '+442083661178'
        mechanism.save()
        self.assertEqual(mechanism.value, '+44 20 8366 1178')
        self.assertEqual(mechanism.value_compact, '+442083661178')

        ContactMechanism.write([mechanism], {
                'value': '+442083661179',
                })
        self.assertEqual(mechanism.value, '+44 20 8366 1179')
        self.assertEqual(mechanism.value_compact, '+442083661179')

        # Test rejection of a phone type mechanism to non-phone value
        with self.assertRaises(UserError):
            mechanism.value = '*****@*****.**'
            mechanism.save()
        transaction.rollback()

        # Test rejection of invalid phone number creation
        with self.assertRaises(UserError):
            mechanism = create('phone', '*****@*****.**')
        transaction.rollback()

        # Test acceptance of a non-phone value when type is non-phone
        mechanism = create('email', '*****@*****.**')
Beispiel #17
0
            def wrapper(*args, **kwargs):
                _db = Tdb._db
                _readonly = True
                if readonly is not None:
                    _readonly = readonly
                elif 'request' in kwargs:
                    _readonly = not (kwargs['request'].method
                                     in ('PUT', 'POST', 'DELETE', 'PATCH'))
                _user = user or 0
                _context = {}

                _retry = Tdb._retry or 0
                _is_open = (Transaction().cursor)

                if not _is_open:
                    with Transaction().start(_db, 0):
                        Cache.clean(_db)
                        _context.update(default_context())
                else:
                    # Transaction().new_cursor(readonly=_readonly)
                    pass
                _context.update(context or {})
                # _context.update({'company': Tdb._company})

                for count in range(_retry, -1, -1):
                    with NoTransaction() if _is_open else Transaction().start(
                            _db, _user, readonly=_readonly, context=_context):
                        cursor = Transaction().cursor
                        if withhold:
                            cursor.cursor.withhold = True
                        try:
                            result = func(*args, **kwargs)
                            if not _readonly:
                                cursor.commit()
                        except DatabaseOperationalError:
                            cursor.rollback()
                            if count and not _readonly:
                                continue
                            raise
                        except Exception:
                            cursor.rollback()
                            raise
                        Cache.resets(_db)
                        return result
Beispiel #18
0
    def test_required_field_missing(self):
        'Test error message when a required field is missing'
        pool = Pool()
        Modelsql = pool.get('test.modelsql')
        transaction = Transaction()

        fields = {
            'desc': '',
            'integer': 0,
        }
        for key, value in fields.items():
            try:
                Modelsql.create([{key: value}])
            except UserError as err:
                # message must not quote key
                msg = "'%s' not missing but quoted in error: '%s'" % (
                    key, err.message)
                self.assertTrue(key not in err.message, msg)
            else:
                self.fail('UserError should be caught')
            transaction.rollback()
Beispiel #19
0
    def test_required_field_missing(self):
        'Test error message when a required field is missing'
        pool = Pool()
        Modelsql = pool.get('test.modelsql')
        transaction = Transaction()

        fields = {
            'desc': '',
            'integer': 0,
            }
        for key, value in fields.iteritems():
            try:
                Modelsql.create([{key: value}])
            except UserError, err:
                # message must not quote key
                msg = "'%s' not missing but quoted in error: '%s'" % (key,
                        err.message)
                self.assertTrue(key not in err.message, msg)
            else:
                self.fail('UserError should be caught')
            transaction.rollback()
def transaction(request):
    """Yields transaction with installed module.
    """

    # Importing transaction directly causes cyclic dependency in 3.6
    from trytond.tests.test_tryton import USER, CONTEXT, DB_NAME, POOL
    from trytond.tools.singleton import Singleton  # noqa
    from trytond.transaction import Transaction
    from trytond.cache import Cache

    # Inject helper functions in instance on which test function was collected.
    request.instance.POOL = POOL
    request.instance.USER = USER
    request.instance.CONTEXT = CONTEXT
    request.instance.DB_NAME = DB_NAME

    transaction = Transaction()

    with transaction.start(DB_NAME, USER, context=CONTEXT) as txn:
        yield txn
        transaction.rollback()
        Cache.drop(DB_NAME)
Beispiel #21
0
    def test_many2many(self):
        'Test many2many'
        pool = Pool()
        Many2many = pool.get('test.import_data.many2many')
        transaction = Transaction()

        self.assertEqual(Many2many.import_data(['many2many'], [['Test 1']]), 1)

        self.assertEqual(
            Many2many.import_data(
                ['many2many:id'],
                [['tests.import_data_many2many_target_test1']]), 1)

        self.assertEqual(
            Many2many.import_data(['many2many'], [['Test 1,Test 2']]), 1)

        self.assertEqual(
            Many2many.import_data(['many2many:id'], [[
                'tests.import_data_many2many_target_test1,'
                'tests.import_data_many2many_target_test2'
            ]]), 1)

        self.assertEqual(
            Many2many.import_data(['many2many'], [['Test\\, comma']]), 1)

        self.assertEqual(
            Many2many.import_data(['many2many'], [['Test\\, comma,Test 1']]),
            1)

        self.assertEqual(Many2many.import_data(['many2many'], [['']]), 1)

        self.assertEqual(
            Many2many.import_data(['many2many'], [['Test 1'], ['Test 2']]), 2)

        with self.assertRaises(ImportDataError):
            Many2many.import_data(['many2many'], [['foo']])
        transaction.rollback()

        with self.assertRaises(ImportDataError):
            Many2many.import_data(['many2many'], [['Test 1,foo']])
        transaction.rollback()

        with self.assertRaises(ImportDataError):
            Many2many.import_data(['many2many'], [['Duplicate']])
        transaction.rollback()

        with self.assertRaises(ImportDataError):
            Many2many.import_data(['many2many'], [['Test 1,Duplicate']])
        transaction.rollback()
def transaction(request):
    """Yields transaction with installed module.
    """

    # Importing transaction directly causes cyclic dependency in 3.6
    from trytond.tests.test_tryton import USER, CONTEXT, DB_NAME, POOL
    from trytond.tools.singleton import Singleton  # noqa
    from trytond.transaction import Transaction
    from trytond.cache import Cache

    # Inject helper functions in instance on which test function was collected.
    request.instance.POOL = POOL
    request.instance.USER = USER
    request.instance.CONTEXT = CONTEXT
    request.instance.DB_NAME = DB_NAME

    transaction = Transaction()

    with transaction.start(DB_NAME, USER, context=CONTEXT) as txn:
        yield txn
        transaction.rollback()
        Cache.drop(DB_NAME)
Beispiel #23
0
    def test_restore_history(self):
        'Test restore history'
        pool = Pool()
        History = pool.get('test.history')
        transaction = Transaction()

        history = History(value=1)
        history.save()
        history_id = history.id
        first = history.create_date

        transaction.commit()

        history = History(history_id)
        history.value = 2
        history.save()

        transaction.commit()

        History.restore_history([history_id], first)
        history = History(history_id)
        self.assertEqual(history.value, 1)

        transaction.rollback()

        History.restore_history([history_id], datetime.datetime.min)
        with self.assertRaises(AccessError):
            History.read([history_id], ['value'])

        transaction.rollback()

        History.delete([History(history_id)])

        transaction.commit()

        History.restore_history([history_id], datetime.datetime.max)
        with self.assertRaises(AccessError):
            History.read([history_id], ['value'])
Beispiel #24
0
    def test_integer_required(self):
        'Test required integer'
        pool = Pool()
        IntegerRequired = pool.get('test.import_data.integer_required')
        transaction = Transaction()

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['1']]), 1)

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['-1']]), 1)

        with self.assertRaises(RequiredValidationError):
            IntegerRequired.import_data(['integer'], [['']])
        transaction.rollback()

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['1'], ['2']]), 2)

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['1.1']])

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['-1.1']])

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['foo']])

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['0']]), 1)

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [[0]]), 1)

        with self.assertRaises(RequiredValidationError):
            IntegerRequired.import_data(['integer'], [[None]])
        transaction.rollback()
Beispiel #25
0
    def test_numeric_required(self):
        'Test required numeric'
        pool = Pool()
        NumericRequired = pool.get('test.import_data.numeric_required')
        transaction = Transaction()

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1.1']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['-1.1']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1']]), 1)

        with self.assertRaises(RequiredValidationError):
            NumericRequired.import_data(['numeric'], [['']])
        transaction.rollback()

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(InvalidOperation,
            NumericRequired.import_data, ['numeric'], [['foo']])

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['0']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['0.0']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [[Decimal('0.0')]]), 1)

        with self.assertRaises(RequiredValidationError):
            NumericRequired.import_data(['numeric'], [[None]])
        transaction.rollback()
Beispiel #26
0
    def test_float_required(self):
        'Test required float'
        pool = Pool()
        FloatRequired = pool.get('test.import_data.float_required')
        transaction = Transaction()

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1.1']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['-1.1']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1']]), 1)

        with self.assertRaises(RequiredValidationError):
            FloatRequired.import_data(['float'], [['']])
        transaction.rollback()

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(ValueError, FloatRequired.import_data,
            ['float'], [['foo']])

        self.assertEqual(FloatRequired.import_data(['float'],
            [['0']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['0.0']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [[0.0]]), 1)

        with self.assertRaises(RequiredValidationError):
            FloatRequired.import_data(['float'], [[None]])
        transaction.rollback()
Beispiel #27
0
    def test_restore_history(self):
        'Test restore history'
        pool = Pool()
        History = pool.get('test.history')
        transaction = Transaction()

        history = History(value=1)
        history.save()
        history_id = history.id
        first = history.create_date

        transaction.commit()

        history = History(history_id)
        history.value = 2
        history.save()

        transaction.commit()

        History.restore_history([history_id], first)
        history = History(history_id)
        self.assertEqual(history.value, 1)

        transaction.rollback()

        History.restore_history([history_id], datetime.datetime.min)
        self.assertRaises(UserError, History.read, [history_id])

        transaction.rollback()

        History.delete([History(history_id)])

        transaction.commit()

        History.restore_history([history_id], datetime.datetime.max)
        self.assertRaises(UserError, History.read, [history_id])
    def test_product(self):
        pool = Pool()
        Recipe = pool.get('dish_recipe.recipe')
        Category = pool.get('dish_recipe.category')
        transaction = Transaction()

        category = Category(name='Category')

        product_1, unit = self._create_product('product_1', 'Unit')
        recipe = Recipe(
            name='Recipe',
            category=category,
            product=product_1,
            quantity=1.0,
            unit=unit,
        )
        recipe.save()
        self.assertEqual(recipe.rec_name, 'Recipe')

        # Do not allow to use a product that already belongs to a recipe
        self.assertRaises(UserError, Recipe.create, [{
            'product': product_1.id,
        }])
        transaction.rollback()
Beispiel #29
0
    def test_many2many(self):
        'Test many2many'
        pool = Pool()
        Many2many = pool.get('test.import_data.many2many')
        transaction = Transaction()

        self.assertEqual(Many2many.import_data(['many2many'],
            [['Test 1']]), 1)

        self.assertEqual(Many2many.import_data(['many2many:id'],
            [['tests.import_data_many2many_target_test1']]), 1)

        self.assertEqual(Many2many.import_data(['many2many'],
            [['Test 1,Test 2']]), 1)

        self.assertEqual(Many2many.import_data(['many2many:id'],
            [['tests.import_data_many2many_target_test1,'
                'tests.import_data_many2many_target_test2']]), 1)

        self.assertEqual(Many2many.import_data(['many2many'],
            [['Test\, comma']]), 1)

        self.assertEqual(Many2many.import_data(['many2many'],
            [['Test\, comma,Test 1']]), 1)

        self.assertEqual(Many2many.import_data(['many2many'],
            [['']]), 1)

        self.assertEqual(Many2many.import_data(['many2many'],
            [['Test 1'], ['Test 2']]), 2)

        self.assertRaises(UserError, Many2many.import_data,
            ['many2many'], [['foo']])
        transaction.rollback()

        self.assertRaises(UserError, Many2many.import_data,
            ['many2many'], [['Test 1,foo']])
        transaction.rollback()

        self.assertRaises(UserError, Many2many.import_data,
            ['many2many'], [['Duplicate']])
        transaction.rollback()

        self.assertRaises(UserError, Many2many.import_data,
            ['many2many'], [['Test 1,Duplicate']])
        transaction.rollback()
Beispiel #30
0
    def test_uom_non_zero_rate_factor(self):
        'Test uom non_zero_rate_factor constraint'
        pool = Pool()
        UomCategory = pool.get('product.uom.category')
        Uom = pool.get('product.uom')
        transaction = Transaction()
        category, = UomCategory.create([{'name': 'Test'}])

        self.assertRaises(Exception, Uom.create, [{
            'name': 'Test',
            'symbol': 'T',
            'category': category.id,
            'rate': 0,
            'factor': 0,
        }])
        transaction.rollback()

        def create():
            category, = UomCategory.create([{'name': 'Test'}])
            return Uom.create([{
                'name': 'Test',
                'symbol': 'T',
                'category': category.id,
                'rate': 1.0,
                'factor': 1.0,
            }])[0]

        uom = create()
        self.assertRaises(Exception, Uom.write, [uom], {
            'rate': 0.0,
        })
        transaction.rollback()

        uom = create()
        self.assertRaises(Exception, Uom.write, [uom], {
            'factor': 0.0,
        })
        transaction.rollback()

        uom = create()
        self.assertRaises(Exception, Uom.write, [uom], {
            'rate': 0.0,
            'factor': 0.0,
        })
        transaction.rollback()
Beispiel #31
0
    def test_uom_non_zero_rate_factor(self):
        'Test uom non_zero_rate_factor constraint'
        pool = Pool()
        UomCategory = pool.get('product.uom.category')
        Uom = pool.get('product.uom')
        transaction = Transaction()
        category, = UomCategory.create([{'name': 'Test'}])

        self.assertRaises(Exception, Uom.create, [{
                'name': 'Test',
                'symbol': 'T',
                'category': category.id,
                'rate': 0,
                'factor': 0,
                }])
        transaction.rollback()

        def create():
            category, = UomCategory.create([{'name': 'Test'}])
            return Uom.create([{
                        'name': 'Test',
                        'symbol': 'T',
                        'category': category.id,
                        'rate': 1.0,
                        'factor': 1.0,
                        }])[0]

        uom = create()
        self.assertRaises(Exception, Uom.write, [uom], {
                'rate': 0.0,
                })
        transaction.rollback()

        uom = create()
        self.assertRaises(Exception, Uom.write, [uom], {
                'factor': 0.0,
                })
        transaction.rollback()

        uom = create()
        self.assertRaises(Exception, Uom.write, [uom], {
                'rate': 0.0,
                'factor': 0.0,
                })
        transaction.rollback()
    def test_constraints(self):
        'Test constraints'
        pool = Pool()
        Model = pool.get('ir.model')
        Trigger = pool.get('ir.trigger')
        transaction = Transaction()

        model, = Model.search([
                ('model', '=', 'test.triggered'),
                ])
        action_model, = Model.search([
                ('model', '=', 'test.trigger_action'),
                ])

        values = {
            'name': 'Test',
            'model': model.id,
            'on_time': True,
            'condition': 'true',
            'action_model': action_model.id,
            'action_function': 'test',
            }
        self.assertTrue(Trigger.create([values]))

        transaction.rollback()

        # on_exclusive
        for i in range(1, 4):
            for combination in combinations(
                    ['create', 'write', 'delete'], i):
                combination_values = values.copy()
                for mode in combination:
                    combination_values['on_%s' % mode] = True
                self.assertRaises(UserError, Trigger.create,
                    [combination_values])
                transaction.rollback()

        # check_condition
        condition_values = values.copy()
        condition_values['condition'] = '='
        self.assertRaises(UserError, Trigger.create,
            [condition_values])
        transaction.rollback()

        # Restart the cache on the get_triggers method of ir.trigger
        Trigger._get_triggers_cache.clear()
    def test_reference(self):
        'Test reference'
        pool = Pool()
        Reference = pool.get('test.import_data.reference')
        transaction = Transaction()

        self.assertEqual(
            Reference.import_data(
                ['reference'],
                [['test.import_data.reference.selection,Test']]), 1)
        reference, = Reference.search([])
        self.assertEqual(reference.reference.__name__,
                         'test.import_data.reference.selection')
        transaction.rollback()

        self.assertEqual(
            Reference.import_data(['reference:id'], [[
                'test.import_data.reference.selection,'
                'tests.import_data_reference_selection_test'
            ]]), 1)
        reference, = Reference.search([])
        self.assertEqual(reference.reference.__name__,
                         'test.import_data.reference.selection')
        transaction.rollback()

        self.assertEqual(Reference.import_data(['reference'], [['']]), 1)
        reference, = Reference.search([])
        self.assertEqual(reference.reference, None)
        transaction.rollback()

        self.assertEqual(
            Reference.import_data(
                ['reference'],
                [['test.import_data.reference.selection,Test'],
                 ['test.import_data.reference.selection,Test']]), 2)
        for reference in Reference.search([]):
            self.assertEqual(reference.reference.__name__,
                             'test.import_data.reference.selection')
        transaction.rollback()

        self.assertRaises(UserError, Reference.import_data, ['reference'],
                          [['test.import_data.reference.selection,foo']])
        transaction.rollback()

        self.assertRaises(UserError, Reference.import_data, ['reference'],
                          [['test.import_data.reference.selection,Duplicate']])
        transaction.rollback()

        self.assertRaises(UserError, Reference.import_data, ['reference:id'],
                          [['test.import_data.reference.selection,foo']])
        transaction.rollback()

        self.assertRaises(Exception, Reference.import_data, ['reference:id'],
                          [['test.import_data.reference.selection,test.foo']])
        transaction.rollback()
Beispiel #34
0
    def test_ordered_search(self):
        'Test ordered search of history models'
        pool = Pool()
        History = pool.get('test.history')
        transaction = Transaction()
        order = [('value', 'ASC')]

        history = History(value=1)
        history.save()
        first_id = history.id
        first_stamp = history.create_date
        transaction.commit()

        history = History(value=2)
        history.save()
        second_id = history.id
        second_stamp = history.create_date

        transaction.commit()

        first, second = History.search([], order=order)

        self.assertEqual(first.id, first_id)
        self.assertEqual(second.id, second_id)

        first.value = 3
        first.save()
        third_stamp = first.write_date
        transaction.commit()

        results = [
            (first_stamp, [first]),
            (second_stamp, [first, second]),
            (third_stamp, [second, first]),
            (datetime.datetime.now(), [second, first]),
            (datetime.datetime.max, [second, first]),
        ]
        for timestamp, instances in results:
            with Transaction().set_context(_datetime=timestamp):
                records = History.search([], order=order)
                self.assertEqual(records, instances)
            transaction.rollback()

        to_delete, _ = History.search([], order=order)

        self.assertEqual(to_delete.id, second.id)

        History.delete([to_delete])
        transaction.commit()

        results = [
            (first_stamp, [first]),
            (second_stamp, [first, second]),
            (third_stamp, [second, first]),
            (datetime.datetime.now(), [first]),
            (datetime.datetime.max, [first]),
        ]
        for timestamp, instances in results:
            with Transaction().set_context(_datetime=timestamp,
                                           from_test=True):
                records = History.search([], order=order)
                self.assertEqual(records, instances)
            transaction.rollback()
Beispiel #35
0
def load_modules(database_name, pool, update=False, lang=None):
    res = True
    if not Transaction().cursor:
        contextmanager = Transaction().start(database_name, 0)
    else:
        contextmanager = contextlib.nested(Transaction().new_cursor(),
                Transaction().set_user(0),
                Transaction().reset_context())
    with contextmanager:
        cursor = Transaction().cursor
        if update:
            # Migration from 2.2: workflow module removed
            cursor.execute('DELETE FROM ir_module_module '
                'WHERE name = %s', ('workflow',))
            if 'all' in CONFIG['init']:
                cursor.execute("SELECT name FROM ir_module_module "
                    "WHERE name != \'test\'")
            else:
                cursor.execute("SELECT name FROM ir_module_module "
                    "WHERE state IN ('installed', 'to install', "
                    "'to upgrade', 'to remove')")
        else:
            cursor.execute("SELECT name FROM ir_module_module "
                "WHERE state IN ('installed', 'to upgrade', 'to remove')")
        module_list = [name for (name,) in cursor.fetchall()]
        if update:
            for module in CONFIG['init'].keys():
                if CONFIG['init'][module]:
                    module_list.append(module)
            for module in CONFIG['update'].keys():
                if CONFIG['update'][module]:
                    module_list.append(module)
        graph = create_graph(module_list)[0]

        try:
            load_module_graph(graph, pool, lang)
        except Exception:
            cursor.rollback()
            raise

        if update:
            cursor.execute("SELECT name FROM ir_module_module "
                "WHERE state IN ('to remove')")
            fetchall = cursor.fetchall()
            if fetchall:
                for (mod_name,) in fetchall:
                    #TODO check if ressource not updated by the user
                    cursor.execute('SELECT model, db_id FROM ir_model_data '
                        'WHERE module = %s '
                        'ORDER BY id DESC', (mod_name,))
                    for rmod, rid in cursor.fetchall():
                        Model = pool.get(rmod)
                        Model.delete([Model(rid)])
                    cursor.commit()
                cursor.execute("UPDATE ir_module_module SET state = %s "
                    "WHERE state IN ('to remove')", ('uninstalled',))
                cursor.commit()
                res = False

            Module = pool.get('ir.module.module')
            Module.update_list()
        cursor.commit()
    Cache.resets(database_name)
    return res
    def test_reconciliation(self):
        pool = Pool()
        Account = pool.get('account.account')
        Receipt = pool.get('cash_bank.receipt')
        Reconciliation = pool.get('cash_bank.reconciliation')
        Line = pool.get('cash_bank.reconciliation.line')
        Config = pool.get('cash_bank.configuration')

        party = self._create_party('Party test', None)

        transaction = Transaction()

        company = create_company()
        with set_company(company):
            create_chart(company)
            create_fiscalyear(company)

            account_transfer, = Account.search([
                ('name', '=', 'Main Expense'),
            ])
            account_cash, = Account.search([
                ('name', '=', 'Main Cash'),
            ])
            account_revenue, = Account.search([
                ('name', '=', 'Main Revenue'),
            ])
            account_expense, = Account.search([
                ('name', '=', 'Main Expense'),
            ])

            config = Config(account_transfer=account_transfer)
            config.save()

            journal = create_journal(company, 'journal_cash')

            sequence = create_sequence('Cash/Bank Sequence',
                                       'cash_bank.receipt', company)
            sequence_convertion = create_sequence('Cash/Bank Convertion',
                                                  'cash_bank.convertion',
                                                  company)
            sequence_reconciliation = create_sequence(
                'Cash/Bank Reconciliation', 'cash_bank.reconciliation',
                company)

            config.convertion_seq = sequence_convertion
            config.reconciliation_seq = sequence_reconciliation
            config.save()

            _, bank_account = create_bank_account(
                party_bank=self._create_party('Party Bank', None),
                party_owner=company.party)

            bank = create_cash_bank(company, 'Main Bank', 'bank', journal,
                                    account_cash, sequence, bank_account)
            self.assertEqual(len(bank.receipt_types), 2)

            date = datetime.date.today()

            rcps = [
                self._get_receipt(company, bank, 'in', date, Decimal('100.0'),
                                  account_revenue),
                self._get_receipt(company, bank, 'in', date, Decimal('200.0'),
                                  account_revenue),
                self._get_receipt(company, bank, 'in', date, Decimal('300.0'),
                                  account_revenue),
                self._get_receipt(company, bank, 'in', date, Decimal('400.0'),
                                  account_revenue),
                self._get_receipt(company, bank, 'out', date, Decimal('10.0'),
                                  account_expense, party),
                self._get_receipt(company, bank, 'out', date, Decimal('20.0'),
                                  account_expense, party),
            ]
            Receipt.save(rcps)
            Receipt.confirm(rcps)

            recon = Reconciliation(
                company=company,
                cash_bank=bank,
                date=date,
                date_start=date,
                date_end=date,
                bank_balance=Decimal(600.0),
                last_bank_balance=Decimal(0.0),
            )
            recon.save()

            Reconciliation.complete_lines([recon])
            self.assertEqual(len(recon.lines), 6)

            transaction.commit()

            with self.assertRaises(UserError):
                # Diff != 0. There is no lines checked
                Reconciliation.confirm([recon])
            transaction.rollback()

            lines = Line.search([
                ('reconciliation', '=', recon.id),
                ('amount', 'in',
                 [Decimal('100.0'),
                  Decimal('200.0'),
                  Decimal('300.0')]),
            ])
            self.assertEqual(len(lines), 3)
            for line in lines:
                line.check = True
            Line.save(lines)
            recon.save()

            self.assertEqual(recon.diff, Decimal('0.0'))
            transaction.commit()

            with self.assertRaises(UserError):
                # Account move lines are not posted
                Reconciliation.confirm([recon])
            transaction.rollback()

            Receipt.post(rcps)
            Reconciliation.confirm([recon])

            # Account moves can not be posted if a confirmed reconciliation
            # invalidates them

            # Same date
            receipt = self._get_receipt(company, bank, 'in', date,
                                        Decimal('99.0'), account_revenue)
            receipt.save()
            Receipt.confirm([receipt])

            transaction.commit()
            with self.assertRaises(UserError):
                Receipt.post([receipt])
            transaction.rollback()

            # Date before
            new_date = date - datetime.timedelta(days=1)
            receipt = self._get_receipt(company, bank, 'in', new_date,
                                        Decimal('99.0'), account_revenue)
            receipt.save()
            Receipt.confirm([receipt])

            transaction.commit()
            with self.assertRaises(UserError):
                Receipt.post([receipt])
            transaction.rollback()

            # Date OK
            new_date = date + datetime.timedelta(days=1)
            receipt = self._get_receipt(company, bank, 'in', new_date,
                                        Decimal('99.0'), account_revenue)
            receipt.save()
            Receipt.confirm([receipt])
            Receipt.post([receipt])
Beispiel #37
0
    def test_ordered_search(self):
        'Test ordered search of history models'
        pool = Pool()
        History = pool.get('test.history')
        transaction = Transaction()
        order = [('value', 'ASC')]

        history = History(value=1)
        history.save()
        first_id = history.id
        first_stamp = history.create_date
        transaction.commit()

        history = History(value=2)
        history.save()
        second_id = history.id
        second_stamp = history.create_date

        transaction.commit()

        first, second = History.search([], order=order)

        self.assertEqual(first.id, first_id)
        self.assertEqual(second.id, second_id)

        first.value = 3
        first.save()
        third_stamp = first.write_date
        transaction.commit()

        results = [
            (first_stamp, [first]),
            (second_stamp, [first, second]),
            (third_stamp, [second, first]),
            (datetime.datetime.now(), [second, first]),
            (datetime.datetime.max, [second, first]),
            ]
        for timestamp, instances in results:
            with Transaction().set_context(_datetime=timestamp):
                records = History.search([], order=order)
                self.assertEqual(records, instances)
            transaction.rollback()

        to_delete, _ = History.search([], order=order)

        self.assertEqual(to_delete.id, second.id)

        History.delete([to_delete])
        transaction.commit()

        results = [
            (first_stamp, [first]),
            (second_stamp, [first, second]),
            (third_stamp, [second, first]),
            (datetime.datetime.now(), [first]),
            (datetime.datetime.max, [first]),
            ]
        for timestamp, instances in results:
            with Transaction().set_context(_datetime=timestamp,
                    from_test=True):
                records = History.search([], order=order)
                self.assertEqual(records, instances)
            transaction.rollback()
Beispiel #38
0
    def test_reference(self):
        'Test reference'
        pool = Pool()
        Reference = pool.get('test.import_data.reference')
        transaction = Transaction()

        self.assertEqual(Reference.import_data(['reference'],
            [['test.import_data.reference.selection,Test']]), 1)
        reference, = Reference.search([])
        self.assertEqual(reference.reference.__name__,
            'test.import_data.reference.selection')
        transaction.rollback()

        self.assertEqual(Reference.import_data(['reference:id'],
            [['test.import_data.reference.selection,'
                'tests.import_data_reference_selection_test']]), 1)
        reference, = Reference.search([])
        self.assertEqual(reference.reference.__name__,
            'test.import_data.reference.selection')
        transaction.rollback()

        self.assertEqual(Reference.import_data(['reference'],
            [['']]), 1)
        reference, = Reference.search([])
        self.assertEqual(reference.reference, None)
        transaction.rollback()

        self.assertEqual(Reference.import_data(['reference'],
            [['test.import_data.reference.selection,Test'],
                ['test.import_data.reference.selection,Test']]), 2)
        for reference in Reference.search([]):
            self.assertEqual(reference.reference.__name__,
                'test.import_data.reference.selection')
        transaction.rollback()

        self.assertRaises(UserError, Reference.import_data,
            ['reference'], [['test.import_data.reference.selection,foo']])
        transaction.rollback()

        self.assertRaises(UserError, Reference.import_data,
            ['reference'],
            [['test.import_data.reference.selection,Duplicate']])
        transaction.rollback()

        self.assertRaises(UserError, Reference.import_data,
            ['reference:id'],
            [['test.import_data.reference.selection,foo']])
        transaction.rollback()

        self.assertRaises(Exception, Reference.import_data,
            ['reference:id'],
            [['test.import_data.reference.selection,test.foo']])
        transaction.rollback()