Pruebas unitarias de Python con CMake

Guía para ejecutar pruebas unitarias en Python y C++ con CMake y ctest en un único build. Configura entornos virtuales por app, descubre tests con unittest y ejecuta pruebas unificadas en CI.

31 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Bienvenido al siguiente pikoTutorial sobre Running Python unit tests with CMake, donde verás cómo ejecutar pruebas unitarias de Python y combinarlas con pruebas de C++ usando un solo comando con CMake y ctest.

Partiremos de una configuración de proyecto con varias aplicaciones. Imagina una carpeta project con app1 y app2 escritas en Python, cada una con su CMakeLists.txt, main.py y requirements.txt, además de una app3 en C++ con su CMakeLists.txt y main.cpp, más un directorio build y el CMakeLists.txt principal en la raíz.

Para habilitar pruebas en Python, amplía la estructura añadiendo en app1 y app2 un directorio test que contenga archivos como test_app.py. La idea es que cada app de Python disponga de su entorno virtual, dependencias instaladas y una carpeta con tests detectables por unittest.

Añadiendo objetivos de prueba: en app1, edita app1/CMakeLists.txt para 1) fijar la ruta del entorno virtual con una variable como APP1_VENV en CMAKE_BINARY_DIR/app1_venv, 2) crear el entorno virtual e instalar requirements mediante una macro o función tipo create_venv, 3) definir un objetivo para ejecutar la aplicación con add_custom_target run_app1 y 4) registrar las pruebas unitarias con add_test, llamando a python -m unittest discover sobre la carpeta app1/test. Repite lo mismo en app2. No olvides activar el subsistema de pruebas con enable_testing() en el CMakeLists.txt de la raíz.

Con esto, basta con ejecutar ctest en la carpeta de build para que se descubran y ejecuten los tests de app1 y app2. Verás algo como Start 1: app1_unit_test y Start 2: app2_unit_test con su estado Passed si todo va bien.

Mezclando pruebas entre lenguajes: además de Python, puedes probar también C++. En app3 añade un directorio test con un archivo test_app.cpp. En app3/CMakeLists.txt crea el ejecutable principal con add_executable main, añade un objetivo run_app3 para ejecutar la app y define un ejecutable de pruebas como add_executable app3_unit_test test/test_app.cpp. Finalmente, registra el test con add_test NAME app3_unit_test COMMAND app3_unit_test. Ahora, un único ctest lanzará las pruebas de Python y C++ de forma unificada.

Recomendaciones prácticas: 1) estructura tus pruebas de Python con nombres tipo test_*.py para que unittest discover las detecte automáticamente; 2) usa entornos virtuales por app para aislar dependencias; 3) en CI puedes añadir ctest -V para salida detallada y ctest -R nombre_parcial para filtrar pruebas; 4) aprovecha etiquetas en CTest para agrupar pruebas de Python y C++ si necesitas ejecuciones selectivas.

En Q2BSTUDIO impulsamos la calidad del software con pipelines de integración continua, pruebas automatizadas y un enfoque sólido de ingeniería. Somos una empresa de desarrollo de software y aplicaciones a medida, expertos en software a medida, inteligencia artificial, ciberseguridad, servicios cloud AWS y Azure, servicios de inteligencia de negocio con Power BI, automatización de procesos, agentes IA e IA para empresas. Si buscas una base técnica robusta para tus productos, descubre cómo abordamos proyectos de aplicaciones a medida con CMake, pruebas y despliegues modernos, o consulta nuestras soluciones de inteligencia artificial para potenciar tu producto con modelos, agentes y analítica avanzada.

Palabras clave de referencia: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat