How do I make a Conan test package require the package that it is testing? Specifically if the package version is dynamic?

Question:

let’s say I have a package:

from conans import ConanFile

class MainLibraryPackage(ConanFile):
    name = 'main'
    description = 'stub'

    def set_version(self):
        self.version = customFunctionToGetVersion()
    ...

And I have a test package for it:

import os
from conans import ConanFile, CMake

class MainLibraryTests(ConanFile):
    """
    Conan recipe to run C++ tests for main library
    """

    settings = 'arch', 'build_type', 'os', 'compiler'
    generators = "cmake"

    def requirements(self):
        self.requires("gtest/1.12.1")
        self.requires(<my main library, somehow?>)

    def build(self):
        cmake = CMake(self)
        cmake.configure()
        cmake.build()

    def test(self):
        print("THIS IS A TEST OF THE TEST")
        if not tools.cross_building(self):
            os.chdir("bin")
            self.run(".%smain_tests" % os.sep)


How do I actually add the main package as a requirement? And if I do so, will that properly populate the CONAN_LIBS variable in the CMakeLists.txt for my test package? Thanks!

Asked By: Danny

||

Answers:

Welcome to the Conan Community!

Your answer depends on which Conan version are you running.

For Conan 1.x, your package is automatically consumed by the test package if you run conan create command. However, if you want to develop step-by-step and run conan test test_package <reference> you need to pass the reference by command line. Still, you don’t need to add your package as a requirement, for both cases, Conan resolves it automatically.

However, Conan 2.x is still in Beta, but very close to be released as stable.
On Conan 2.x, the test package will no longer manage your package automatically, you will need to declare as a requirement, exactly what are you doing in your question. And, this behavior is compatible with Conan 1.x, if you add the attribute test_type = "explicit" in the test_package/conanfile.py

So answering your question, you should use:

self.requires(self.tested_reference_str)

The self.tested_reference_str will resolve your package reference automatically for you, so you don’t need to care about which version or name, it will the same used by your Conan command.

For further information, I recommend you reading the official documentation:

The getting started there is section about testing your package: https://docs.conan.io/en/latest/creating_packages/getting_started.html#getting-started

How to prepare your test_package for Conan 2.x: https://docs.conan.io/en/latest/migrating_to_2.0/recipes.html#changes-in-the-test-package-recipe

Answered By: uilianries
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.