Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • eLearning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Información
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Food & Hospitality
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Guest House
    • Distribuidor de bebidas
    • Hotel
    Real Estate
    • Real Estate Agency
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consulting
    • Accounting Firm
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Trades
    • Handyman
    • Hardware y asistencia informática
    • Solar Energy Systems
    • Zapatero
    • Servicios de limpieza
    • HVAC Services
    Others
    • Nonprofit Organization
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Browse all Industries
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Services for Partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Need help to pass the cloud test.

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
developmentconfigurationcontributiondebug
2 Respuestas
1393 Vistas
Avatar
Anup Ghosh

I have developed a custom module by inherited the product template. There I have added some custom required field. It works perfectly in local.
But when I pushed the code it fails on test case and build also failed. 
Because of the required field doesn't set while testing.

0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,


This is a common issue when you add a required field to a core model like 'product.template'  everything works locally because you're manually filling in the required field, but in automated tests (like Odoo.sh builds or CI pipelines), test records and demo data that create products don't set your new field, causing the tests to fail.

Solution

* Provide a Default Value (Recommended)

Add a default value or compute method so that the field doesn't break existing logic:

from odoo import fields, models

class ProductTemplate(models.Model):
_inherit = 'product.template'

my_required_field = fields.Char(
string="My Required Field",
required=True,
default='Default Value'
)


Hope it helps

0
Avatar
Descartar
Anup Ghosh
Autor

If I set a default value for the field, there's a possibility that someone could inadvertently create a product without altering that default value, which would allow them to submit the product entity. How can this issue be addressed?

Avatar
Piyush H
Mejor respuesta

Hello Anup,

Okay, I understand. You've added required fields to the product.template model in a custom module, and your Odoo Cloud tests are failing because these fields aren't being populated during the automated testing process. Here's a breakdown of how to address this, focusing on making your module cloud-test-friendly:

Understanding the Problem

Odoo Cloud tests run automatically when you push code to platforms like Odoo.sh. These tests are designed to ensure your module doesn't break existing functionality. Because your new fields are required, the tests are likely failing when Odoo tries to create or modify product templates without those fields being filled in.

Solutions

Here's a multi-pronged approach to solve this:

  1. Provide Default Values in Tests:
    • Data Files (XML): The best practice is to create XML data files within your module's data/ directory (e.g., data/test_data.xml). These files will be loaded during testing and can be used to create or update product templates, ensuring your required fields are populated.
    <!-- data/test_data.xml -->
    <odoo>
        <data noupdate="1">
            <record id="product_template_test_1" model="product.template">
                <field name="name">Test Product</field>
                <!-- Fill in your required fields here -->
                <field name="your_required_field_1">Some Value</field>
                <field name="your_required_field_2">Another Value</field>
                <field name="type">product</field>
            </record>
        </data>
    </odoo>
    
    • noupdate="1": This is important! It ensures that the data is loaded only during module installation/testing and won't be overwritten during upgrades.
    • Manifest File: Make sure your __manifest__.py file includes the data file:
    # __manifest__.py
    {
        'name': 'Your Module Name',
        'version': '1.0',
        'depends': ['product'],
        'data': [
            'data/test_data.xml',
        ],
    }
    
  2. Test Case Modifications (If Necessary):
    • If your module includes Python-based test cases (in the tests/ directory), you might need to modify those tests to create or update product templates, again ensuring your required fields are set.
    # tests/test_your_module.py
    from odoo.tests import common
    
    class TestYourModule(common.TransactionCase):
    
        def test_product_creation(self):
            product = self.env['product.template'].create({
                'name': 'Test Product',
                'your_required_field_1': 'Value for Test',
                'your_required_field_2': 'Another Test Value',
                'type': 'product',
            })
            self.assertEqual(product.name, 'Test Product')
            # Add more assertions to validate your logic
    
  3. Conditional Requirements (Less Ideal, but Sometimes Necessary):
    • As a last resort (and generally not recommended if you can avoid it), you could make the fields conditionally required. For example, only required if a specific setting is enabled. This adds complexity and might not be the best design.
    from odoo import models, fields, api
    
    class ProductTemplate(models.Model):
        _inherit = 'product.template'
    
        your_required_field_1 = fields.Char(string="Required Field 1")
        your_required_field_2 = fields.Char(string="Required Field 2")
    
        @api.constrains('your_required_field_1', 'your_required_field_2')
        def _check_required_fields(self):
            # Example: Only require the fields if a specific company setting is enabled
            if self.env.company.some_setting:
                for record in self:
                    if not record.your_required_field_1 or not record.your_required_field_2:
                        raise ValidationError("Required fields must be filled in when the setting is enabled.")
    
    • Important: If you use conditional requirements, make sure your tests cover both scenarios (setting enabled and disabled).

Example Scenario

Let's say you added a required field called manufacturer (a Char field) to product.template.

  1. data/test_data.xml:
    <odoo>
        <data noupdate="1">
            <record id="product_template_test_1" model="product.template">
                <field name="name">Test Product</field>
                <field name="manufacturer">Acme Corp</field>
                <field name="type">product</field>
            </record>
        </data>
    </odoo>
    
  2. __manifest__.py:
    {
        'name': 'Product Manufacturer',
        'version': '1.0',
        'depends': ['product'],
        'data': [
            'data/test_data.xml',
        ],
    }
    

Key Considerations

  • Data Consistency: Ensure the data you provide in your test files is valid and consistent with your module's logic.
  • Test Coverage: Write comprehensive tests to cover all possible scenarios and edge cases related to your new fields.
  • Odoo.sh Logs: Carefully examine the Odoo.sh build logs to understand the exact error messages and traceback. This will help you pinpoint the cause of the test failures.
  • Dependencies: Double-check that your module correctly declares its dependency on the product module.
  • Upgradeability: Think about how your module will behave during upgrades. The noupdate="1" attribute in your data files is crucial for this.

By providing default values for your required fields in your test data, you should be able to resolve the test failures and get your module building successfully on the Odoo Cloud platform. Remember to test thoroughly!

🚀 Did This Solve Your Problem?

If this answer helped you save time, money, or frustration, consider:

✅ Upvoting (👍) to help others find it faster

✅ Marking as "Best Answer" if it resolved your issue

Your feedback keeps the Odoo community strong! 💪

(Need further customization? Drop a comment—I’m happy to refine the solution!)

0
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
[Aide] Modules custom non détectés ou non exécutés sur Odoo 18 (Windows)
development configuration debug
Avatar
Avatar
1
oct 25
683
My Custom Module don't show in apps list after update.
development configuration debug
Avatar
Avatar
Avatar
2
ago 25
1305
Creating a field in res.user is throwing internal server error
development configuration debug
Avatar
Avatar
Avatar
2
jun 25
1507
Cron job completes Instantly on production without throwing errors – works correctly on dev Resuelto
development configuration function debug
Avatar
Avatar
2
sept 25
1135
Hide invoice header and footer in odoo v17 Enterprise
development configuration accounting debug
Avatar
Avatar
1
jun 25
1476
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now