def test_cmake_toolchain_multiple_user_toolchain():
    """ A consumer consuming two packages that declare:
            self.conf_info["tools.cmake.cmaketoolchain:user_toolchain"]
        The consumer wants to use apply both toolchains in the CMakeToolchain.
        There are two ways to customize the CMakeToolchain (parametrized):
                1. Altering the context of the block (with_context = True)
                2. Using the t.blocks["user_toolchain"].user_toolchains = [] (with_context = False)
    """
    client = TestClient()
    conanfile = textwrap.dedent("""
        import os
        from conans import ConanFile
        class Pkg(ConanFile):
            exports_sources = "*"
            def package(self):
                self.copy("*")
            def package_info(self):
                f = os.path.join(self.package_folder, "mytoolchain.cmake")
                self.conf_info["tools.cmake.cmaketoolchain:user_toolchain"] = f
        """)
    client.save({
        "conanfile.py":
        conanfile,
        "mytoolchain.cmake":
        'message(STATUS "mytoolchain1.cmake !!!running!!!")'
    })
    client.run("create . toolchain1/0.1@")
    client.save({
        "conanfile.py":
        conanfile,
        "mytoolchain.cmake":
        'message(STATUS "mytoolchain2.cmake !!!running!!!")'
    })
    client.run("create . toolchain2/0.1@")

    conanfile = textwrap.dedent("""
        from conans import ConanFile
        from conan.tools.cmake import CMake, CMakeToolchain
        class Pkg(ConanFile):
            settings = "os", "compiler", "arch", "build_type"
            exports_sources = "CMakeLists.txt"
            tool_requires = "toolchain1/0.1", "toolchain2/0.1"


            def generate(self):
                # Get the toolchains from "tools.cmake.cmaketoolchain:user_toolchain" conf at the
                # tool_requires
                user_toolchains = []
                for dep in self.dependencies.direct_build.values():
                    ut = dep.conf_info["tools.cmake.cmaketoolchain:user_toolchain"]
                    if ut:
                        user_toolchains.append(ut.replace('\\\\', '/'))

                # Modify the context of the user_toolchain block
                t = CMakeToolchain(self)
                t.blocks["user_toolchain"].values["paths"] = user_toolchains
                t.generate()

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

    client.save({
        "conanfile.py": conanfile,
        "CMakeLists.txt": gen_cmakelists()
    },
                clean_first=True)
    client.run("create . pkg/0.1@")
    assert "mytoolchain1.cmake !!!running!!!" in client.out
    assert "mytoolchain2.cmake !!!running!!!" in client.out
Example #2
0
    def test_package_info_components_complete(self):
        dep = textwrap.dedent("""
            import os
            from conans import ConanFile
            class Dep(ConanFile):
                exports_sources = "*"
                def package(self):
                    self.copy("*")
                def package_info(self):
                    self.cpp_info.name = "Galaxy"
                    self.cpp_info.components["Starlight"].includedirs = [os.path.join("galaxy", "starlight")]
                    self.cpp_info.components["Starlight"].libs = ["libstarlight"]
                    self.cpp_info.components["Planet"].includedirs = [os.path.join("galaxy", "planet")]
                    self.cpp_info.components["Planet"].libs = ["libplanet"]
                    self.cpp_info.components["Planet"].requires = ["Starlight"]
                    self.cpp_info.components["Launcher"].system_libs = ["ground"]
                    self.cpp_info.components["ISS"].includedirs = [os.path.join("galaxy", "iss")]
                    self.cpp_info.components["ISS"].libs = ["libiss"]
                    self.cpp_info.components["ISS"].libdirs = ["iss_libs"]
                    self.cpp_info.components["ISS"].system_libs = ["solar", "magnetism"]
                    self.cpp_info.components["ISS"].requires = ["Starlight", "Launcher"]
        """)
        consumer = textwrap.dedent("""
        from conans import ConanFile
        class Consumer(ConanFile):
            requires = "dep/1.0@us/ch"
            def build(self):
                # Global values
                self.output.info("GLOBAL Include paths: %s" % list(self.deps_cpp_info.include_paths))
                self.output.info("GLOBAL Library paths: %s" % list(self.deps_cpp_info.lib_paths))
                self.output.info("GLOBAL Binary paths: %s" % list(self.deps_cpp_info.bin_paths))
                self.output.info("GLOBAL Libs: %s" % list(self.deps_cpp_info.libs))
                self.output.info("GLOBAL System libs: %s" % list(self.deps_cpp_info.system_libs))
                # Deps values
                for dep_key, dep_value in self.deps_cpp_info.dependencies:
                    self.output.info("DEPS name: %s" % dep_value.get_name('txt'))
                    self.output.info("DEPS Include paths: %s" % list(dep_value.include_paths))
                    self.output.info("DEPS Library paths: %s" % list(dep_value.lib_paths))
                    self.output.info("DEPS Binary paths: %s" % list(dep_value.bin_paths))
                    self.output.info("DEPS Libs: %s" % list(dep_value.libs))
                    self.output.info("DEPS System libs: %s" % list(dep_value.system_libs))
                # Components values
                for dep_key, dep_value in self.deps_cpp_info.dependencies:
                    for comp_name, comp_value in dep_value.components.items():
                        self.output.info("COMP %s Include paths: %s" % (comp_name,
                            list(comp_value.include_paths)))
                        self.output.info("COMP %s Library paths: %s" % (comp_name, list(comp_value.lib_paths)))
                        self.output.info("COMP %s Binary paths: %s" % (comp_name, list(comp_value.bin_paths)))
                        self.output.info("COMP %s Libs: %s" % (comp_name, list(comp_value.libs)))
                        self.output.info("COMP %s Requires: %s" % (comp_name, list(comp_value.requires)))
                        self.output.info("COMP %s System libs: %s" % (comp_name, list(comp_value.system_libs)))
        """)

        client = TestClient()
        client.save({
            "conanfile_dep.py": dep,
            "conanfile_consumer.py": consumer,
            "galaxy/starlight/starlight.h": "",
            "lib/libstarlight": "",
            "galaxy/planet/planet.h": "",
            "lib/libplanet": "",
            "galaxy/iss/iss.h": "",
            "iss_libs/libiss": "",
            "bin/exelauncher": ""
        })
        dep_ref = ConanFileReference("dep", "1.0", "us", "ch")
        dep_pref = PackageReference(dep_ref, NO_SETTINGS_PACKAGE_ID)
        client.run("create conanfile_dep.py dep/1.0@us/ch")
        client.run("create conanfile_consumer.py consumer/1.0@us/ch")
        package_folder = client.cache.package_layout(dep_ref).package(dep_pref)

        expected_comp_starlight_include_paths = [
            os.path.join(package_folder, "galaxy", "starlight")
        ]
        expected_comp_planet_include_paths = [
            os.path.join(package_folder, "galaxy", "planet")
        ]
        expected_comp_launcher_include_paths = []
        expected_comp_iss_include_paths = [
            os.path.join(package_folder, "galaxy", "iss")
        ]
        expected_comp_starlight_library_paths = [
            os.path.join(package_folder, "lib")
        ]
        expected_comp_launcher_library_paths = [
            os.path.join(package_folder, "lib")
        ]
        expected_comp_planet_library_paths = [
            os.path.join(package_folder, "lib")
        ]
        expected_comp_iss_library_paths = [
            os.path.join(package_folder, "iss_libs")
        ]
        expected_comp_starlight_binary_paths = [
            os.path.join(package_folder, "bin")
        ]
        expected_comp_launcher_binary_paths = [
            os.path.join(package_folder, "bin")
        ]
        expected_comp_planet_binary_paths = [
            os.path.join(package_folder, "bin")
        ]
        expected_comp_iss_binary_paths = [os.path.join(package_folder, "bin")]

        expected_global_include_paths = expected_comp_planet_include_paths + \
            expected_comp_iss_include_paths + expected_comp_starlight_include_paths
        expected_global_library_paths = expected_comp_starlight_library_paths + \
            expected_comp_iss_library_paths
        expected_global_binary_paths = expected_comp_starlight_binary_paths

        self.assertIn(
            "GLOBAL Include paths: %s" % expected_global_include_paths,
            client.out)
        self.assertIn(
            "GLOBAL Library paths: %s" % expected_global_library_paths,
            client.out)
        self.assertIn("GLOBAL Binary paths: %s" % expected_global_binary_paths,
                      client.out)
        self.assertIn("GLOBAL Libs: ['libplanet', 'libiss', 'libstarlight']",
                      client.out)
        self.assertIn("GLOBAL System libs: ['solar', 'magnetism', 'ground']",
                      client.out)

        self.assertIn("DEPS name: Galaxy", client.out)
        self.assertIn("DEPS Include paths: %s" % expected_global_include_paths,
                      client.out)
        self.assertIn("DEPS Library paths: %s" % expected_global_library_paths,
                      client.out)
        self.assertIn("DEPS Binary paths: %s" % expected_global_binary_paths,
                      client.out)
        self.assertIn("DEPS Libs: ['libplanet', 'libiss', 'libstarlight']",
                      client.out)
        self.assertIn("DEPS System libs: ['solar', 'magnetism', 'ground']",
                      client.out)

        self.assertIn(
            "COMP Starlight Include paths: %s" %
            list(expected_comp_starlight_include_paths), client.out)
        self.assertIn(
            "COMP Planet Include paths: %s" %
            list(expected_comp_planet_include_paths, ), client.out)
        self.assertIn(
            "COMP Launcher Include paths: %s" %
            list(expected_comp_launcher_include_paths), client.out)
        self.assertIn(
            "COMP ISS Include paths: %s" %
            list(expected_comp_iss_include_paths), client.out)
        self.assertIn(
            "COMP Starlight Library paths: %s" %
            list(expected_comp_starlight_library_paths), client.out)
        self.assertIn(
            "COMP Planet Library paths: %s" %
            list(expected_comp_planet_library_paths), client.out)
        self.assertIn(
            "COMP Launcher Library paths: %s" %
            list(expected_comp_launcher_library_paths), client.out)
        self.assertIn(
            "COMP ISS Library paths: %s" %
            list(expected_comp_iss_library_paths), client.out)
        self.assertIn(
            "COMP Starlight Binary paths: %s" %
            list(expected_comp_iss_binary_paths), client.out)
        self.assertIn(
            "COMP Planet Binary paths: %s" %
            list(expected_comp_planet_binary_paths), client.out)
        self.assertIn(
            "COMP Launcher Binary paths: %s" %
            list(expected_comp_launcher_binary_paths), client.out)
        self.assertIn(
            "COMP ISS Binary paths: %s" % list(expected_comp_iss_binary_paths),
            client.out)
        self.assertIn("COMP Starlight Libs: ['libstarlight']", client.out)
        self.assertIn("COMP Planet Libs: ['libplanet']", client.out)
        self.assertIn("COMP Launcher Libs: []", client.out)
        self.assertIn("COMP ISS Libs: ['libiss']", client.out)
        self.assertIn("COMP Starlight System libs: []", client.out)
        self.assertIn("COMP Planet System libs: []", client.out)
        self.assertIn("COMP Launcher System libs: ['ground']", client.out)
        self.assertIn("COMP ISS System libs: ['solar', 'magnetism']",
                      client.out)
        self.assertIn("COMP Starlight Requires: []", client.out)
        self.assertIn("COMP Launcher Requires: []", client.out)
        self.assertIn("COMP Planet Requires: ['Starlight']", client.out)
        self.assertIn("COMP ISS Requires: ['Starlight', 'Launcher']",
                      client.out)
Example #3
0
 def setUp(self):
     test_server = TestServer()
     self.servers = {"default": test_server}
     self.client = TestClient(servers=self.servers,
                              users={"default": [("lasote", "mypass")]})
def test_no_soname_flag():
    """ This test case is testing this graph structure:
            *   'LibNoSoname' -> 'OtherLib' -> 'Executable'
        Where:
            *   LibNoSoname: is a package built as shared and without the SONAME flag.
            *   OtherLib: is a package which requires LibNoSoname.
            *   Executable: is the final consumer building an application and depending on OtherLib.
    """
    client = TestClient()
    conanfile = textwrap.dedent("""
    from conans import ConanFile
    from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout

    class {name}Conan(ConanFile):
        name = "{name}"
        version = "1.0"

        # Binary configuration
        settings = "os", "compiler", "build_type", "arch"
        options = {{"shared": [True, False], "fPIC": [True, False]}}
        default_options = {{"shared": True, "fPIC": True}}

        # Sources are located in the same place as this recipe, copy them to the recipe
        exports_sources = "CMakeLists.txt", "src/*"
        {generators}
        {requires}

        def config_options(self):
            if self.settings.os == "Windows":
                del self.options.fPIC

        def layout(self):
            cmake_layout(self)

        def generate(self):
            tc = CMakeToolchain(self)
            tc.generate()

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

        def package(self):
            cmake = CMake(self)
            cmake.install()

        def package_info(self):
            self.cpp_info.libs = ["{name}"]
    """)
    cmakelists_nosoname = textwrap.dedent("""
        cmake_minimum_required(VERSION 3.15)
        project(nosoname CXX)

        add_library(nosoname SHARED src/nosoname.cpp)

        # Adding NO_SONAME flag to main library
        set_target_properties(nosoname PROPERTIES PUBLIC_HEADER "src/nosoname.h" NO_SONAME 1)
        install(TARGETS nosoname DESTINATION "."
                PUBLIC_HEADER DESTINATION include
                RUNTIME DESTINATION bin
                ARCHIVE DESTINATION lib
                LIBRARY DESTINATION lib
                )
    """)
    cpp = gen_function_cpp(name="nosoname")
    h = gen_function_h(name="nosoname")
    client.save({
        "CMakeLists.txt":
        cmakelists_nosoname,
        "src/nosoname.cpp":
        cpp,
        "src/nosoname.h":
        h,
        "conanfile.py":
        conanfile.format(name="nosoname", requires="", generators="")
    })
    # Now, let's create both libraries
    client.run("create .")
    cmakelists_libB = textwrap.dedent("""
    cmake_minimum_required(VERSION 3.15)
    project(libB CXX)

    find_package(nosoname CONFIG REQUIRED)

    add_library(libB SHARED src/libB.cpp)
    target_link_libraries(libB nosoname::nosoname)

    set_target_properties(libB PROPERTIES PUBLIC_HEADER "src/libB.h")
    install(TARGETS libB DESTINATION "."
            PUBLIC_HEADER DESTINATION include
            RUNTIME DESTINATION bin
            ARCHIVE DESTINATION lib
            LIBRARY DESTINATION lib
            )
    """)
    cpp = gen_function_cpp(name="libB",
                           includes=["nosoname"],
                           calls=["nosoname"])
    h = gen_function_h(name="libB")
    client.save(
        {
            "CMakeLists.txt":
            cmakelists_libB,
            "src/libB.cpp":
            cpp,
            "src/libB.h":
            h,
            "conanfile.py":
            conanfile.format(name="libB",
                             requires='requires = "nosoname/1.0"',
                             generators='generators = "CMakeDeps"')
        },
        clean_first=True)
    # Now, let's create both libraries
    client.run("create .")
    # Now, let's create the application consuming libB
    cmakelists = textwrap.dedent("""
        cmake_minimum_required(VERSION 3.15)
        project(PackageTest CXX)

        find_package(libB CONFIG REQUIRED)

        add_executable(example src/example.cpp)
        target_link_libraries(example libB::libB)
    """)
    conanfile = textwrap.dedent("""
        [requires]
        libB/1.0

        [generators]
        CMakeDeps
        CMakeToolchain
    """)
    cpp = gen_function_cpp(name="main", includes=["libB"], calls=["libB"])
    client.save(
        {
            "CMakeLists.txt":
            cmakelists.format(current_folder=client.current_folder),
            "src/example.cpp":
            cpp,
            "conanfile.txt":
            conanfile
        },
        clean_first=True)
    client.run('install . ')
    client.run_command(
        'cmake -G "Unix Makefiles" -DCMAKE_TOOLCHAIN_FILE="./conan_toolchain.cmake" .'
        ' && cmake --build . && ./example')
 def setUp(self):
     self.client = TestClient()
Example #6
0
    def test_add_new_file(self):
        """ Validate issue #5320
        """

        conanfile = dedent("""
            from conans import ConanFile, tools
            import os
            
            class ConanFileToolsTest(ConanFile):
                name = "foobar"
                version = "0.1.0"
                exports_sources = "*"
            
                def build(self):
                    tools.patch(patch_file="add_files.patch")
                    assert os.path.isfile("foo.txt")
                    assert os.path.isfile("bar.txt")
        """)
        bar = "no creo en brujas"
        patch = dedent("""
            From c66347c66991b6e617d107b505c18b3115624b8a Mon Sep 17 00:00:00 2001
            From: Uilian Ries <*****@*****.**>
            Date: Wed, 16 Oct 2019 14:31:34 -0300
            Subject: [PATCH] add foo
            
            ---
             bar.txt | 3 ++-
             foo.txt | 3 +++
             2 files changed, 5 insertions(+), 1 deletion(-)
             create mode 100644 foo.txt
            
            diff --git a/bar.txt b/bar.txt
            index 0f4ff3a..0bd3158 100644
            --- a/bar.txt
            +++ b/bar.txt
            @@ -1 +1,2 @@
            -no creo en brujas
            +Yo no creo en brujas, pero que las hay, las hay
            +
            diff --git a/foo.txt b/foo.txt
            new file mode 100644
            index 0000000..91e8c0d
            --- /dev/null
            +++ b/foo.txt
            @@ -0,0 +1,3 @@
            +For us, there is no spring.
            +Just the wind that smells fresh before the storm.
            +
            -- 
            2.23.0


        """)

        client = TestClient()
        client.save({
            "conanfile.py": conanfile,
            "add_files.patch": patch,
            "bar.txt": bar
        })
        client.run("install .")
        client.run("build .")
        bar_content = load(os.path.join(client.current_folder, "bar.txt"))
        self.assertIn(
            dedent("""Yo no creo en brujas, pero que las hay, las hay
                             """), bar_content)
        foo_content = load(os.path.join(client.current_folder, "foo.txt"))
        self.assertIn(
            dedent("""For us, there is no spring.
Just the wind that smells fresh before the storm."""), foo_content)
        self.assertIn("Running build()", client.out)
        self.assertNotIn("Warning", client.out)
Example #7
0
def test_missing_subarguments():
    """ config MUST run  with a subcommand. Otherwise, it MUST exits with error.
    """
    client = TestClient()
    client.run("config", assert_error=True)
    assert "ERROR: Exiting with code: 2" in client.out
 def test_local_monorepo_chdir(self):
     t = TestClient(path_with_spaces=False)
     t.run_command("svn co {} .".format(self.url))
     self._run_local_test(t, os.path.join(t.current_folder, "lib1"), self.path_to_conanfile)
 def test_remote_root_folder(self):
     t = TestClient(path_with_spaces=False)
     t.run_command("svn co {}/lib1 .".format(self.url))
     self._run_remote_test(t, t.current_folder, self.path_to_conanfile)
     self.assertIn("Repo origin deduced by 'auto':", t.out)
Example #10
0
    def conan_test_test(self):
        '''Checks --build in test command'''
        client_a = TestClient(servers=self.servers,
                              users={
                                  "default": [("lasote", "mypass")],
                                  "local": [("lasote", "mypass")]
                              })
        client_b = TestClient(servers=self.servers,
                              users={
                                  "default": [("lasote", "mypass")],
                                  "local": [("lasote", "mypass")]
                              })

        # Upload Hello0 to local and default from client_a
        self._create(client_a, "Hello0", "0.0")
        client_a.run("upload Hello0/0.0@lasote/stable -r local")
        client_a.run("upload Hello0/0.0@lasote/stable -r default")
        client_a.run("remote list_ref")
        self.assertIn("Hello0/0.0@lasote/stable: local",
                      str(client_a.user_io.out))
        sleep(1)  # For timestamp and updates checks

        # Download Hello0 from local with client_b
        client_b.run(
            "install Hello0/0.0@lasote/stable -r local --build missing")
        client_b.run("remote list_ref")
        self.assertIn("Hello0/0.0@lasote/stable: local",
                      str(client_b.user_io.out))

        # Update Hello0 with client_a and reupload
        self._create(client_a, "Hello0", "0.0", modifier="\n")
        client_a.run("upload Hello0/0.0@lasote/stable -r local")

        # Execute info method in client_b, should advise that there is an update
        client_b.run("info Hello0/0.0@lasote/stable -u")
        self.assertIn("Recipe: Update available", client_b.out)
        self.assertIn("Binary: Cache", client_b.out)

        # Now try to update the package with install -u
        client_b.run("remote list_ref")
        self.assertIn("Hello0/0.0@lasote/stable: local",
                      str(client_b.user_io.out))
        client_b.run("install Hello0/0.0@lasote/stable -u --build")
        client_b.run("remote list_ref")
        self.assertIn("Hello0/0.0@lasote/stable: local",
                      str(client_b.user_io.out))

        # Upload a new version from client A, but only to the default server (not the ref-listed)
        # Upload Hello0 to local and default from client_a
        sleep(1)  # For timestamp and updates checks
        self._create(client_a, "Hello0", "0.0", modifier="\n\n")
        client_a.run("upload Hello0/0.0@lasote/stable -r default")

        # Now client_b checks for updates without -r parameter
        client_b.run("info Hello0/0.0@lasote/stable -u")
        self.assertIn("    Remote: local", str(client_b.user_io.out))
        self.assertIn("    Recipe: Cache", client_b.out)

        # But if we connect to default, should tell us that there is an update IN DEFAULT!
        client_b.run("info Hello0/0.0@lasote/stable -r default -u")
        self.assertIn("Remote: local", str(client_b.user_io.out))
        client_b.run("remote list_ref")
        self.assertIn("Hello0/0.0@lasote/stable: local",
                      str(client_b.user_io.out))

        # Well, now try to update the package with -r default -u
        client_b.run("install Hello0/0.0@lasote/stable -r default -u --build")
        self.assertIn("Hello0/0.0@lasote/stable: Calling build()",
                      str(client_b.user_io.out))
        client_b.run("info Hello0/0.0@lasote/stable -u")
        self.assertIn("Recipe: Cache", client_b.out)
        self.assertIn("Binary: Cache", client_b.out)
 def test_local_root_folder(self):
     t = TestClient(path_with_spaces=False)
     t.run_command("svn co {}/lib1 .".format(self.url))
     self._run_local_test(t, t.current_folder, self.path_to_conanfile)
Example #12
0
    def test_python_requires_with_alias(self, use_alias, use_alias_of_alias):
        assert use_alias if use_alias_of_alias else True
        version_str = "latest2" if use_alias_of_alias else "latest" if use_alias else "1.0"
        client = TestClient()

        # Create python_requires
        client.save({
            CONANFILE:
            """
from conans import ConanFile

class PythonRequires0(ConanFile):

    def build(self):
        super(PythonRequires0, self).build()
        self.output.info(">>> PythonRequires0::build (v={{}})".format(self.version))
        """.format(v=version_str)
        })
        client.run("export . python_requires0/1.0@jgsogo/test")
        client.run("alias python_requires0/latest@jgsogo/test "
                   "python_requires0/1.0@jgsogo/test")
        client.run("alias python_requires0/latest2@jgsogo/test "
                   "python_requires0/latest@jgsogo/test")

        # Create python requires, that require the previous one
        client.save({
            CONANFILE:
            """
from conans import ConanFile, python_requires

base = python_requires("python_requires0/{v}@jgsogo/test")

class PythonRequires1(base.PythonRequires0):
    def build(self):
        super(PythonRequires1, self).build()
        self.output.info(">>> PythonRequires1::build (v={{}})".format(self.version))
        """.format(v=version_str)
        })
        client.run("export . python_requires1/1.0@jgsogo/test")
        client.run(
            "alias python_requires1/latest@jgsogo/test python_requires1/1.0@jgsogo/test"
        )
        client.run(
            "alias python_requires1/latest2@jgsogo/test python_requires1/latest@jgsogo/test"
        )

        # Create python requires
        client.save({
            CONANFILE:
            """
from conans import ConanFile, python_requires

class PythonRequires11(ConanFile):
    def build(self):
        super(PythonRequires11, self).build()
        self.output.info(">>> PythonRequires11::build (v={{}})".format(self.version))
        """.format(v=version_str)
        })
        client.run("export . python_requires11/1.0@jgsogo/test")
        client.run(
            "alias python_requires11/latest@jgsogo/test python_requires11/1.0@jgsogo/test"
        )
        client.run("alias python_requires11/latest2@jgsogo/test "
                   "python_requires11/latest@jgsogo/test")

        # Create python requires, that require the previous one
        client.save({
            CONANFILE:
            """
from conans import ConanFile, python_requires

base = python_requires("python_requires0/{v}@jgsogo/test")

class PythonRequires22(base.PythonRequires0):
    def build(self):
        super(PythonRequires22, self).build()
        self.output.info(">>> PythonRequires22::build (v={{}})".format(self.version))
        """.format(v=version_str)
        })
        client.run("export . python_requires22/1.0@jgsogo/test")
        client.run(
            "alias python_requires22/latest@jgsogo/test python_requires22/1.0@jgsogo/test"
        )
        client.run(
            "alias python_requires22/latest2@jgsogo/test python_requires22/latest@jgsogo/test"
        )

        # Another python_requires, that requires the previous python requires
        client.save({
            CONANFILE:
            """
from conans import ConanFile, python_requires

base_class = python_requires("python_requires1/{v}@jgsogo/test")
base_class2 = python_requires("python_requires11/{v}@jgsogo/test")

class PythonRequires2(base_class.PythonRequires1, base_class2.PythonRequires11):

    def build(self):
        super(PythonRequires2, self).build()
        self.output.info(">>> PythonRequires2::build (v={{}})".format(self.version))
        """.format(v=version_str)
        })
        client.run("export . python_requires2/1.0@jgsogo/test")
        client.run(
            "alias python_requires2/latest@jgsogo/test python_requires2/1.0@jgsogo/test"
        )
        client.run(
            "alias python_requires2/latest2@jgsogo/test python_requires2/latest@jgsogo/test"
        )

        # My project, will consume the latest python requires
        client.save({
            CONANFILE:
            """
from conans import ConanFile, python_requires

base_class = python_requires("python_requires2/{v}@jgsogo/test")
base_class2 = python_requires("python_requires22/{v}@jgsogo/test")

class Project(base_class.PythonRequires2, base_class2.PythonRequires22):

    def build(self):
        super(Project, self).build()
        self.output.info(">>> Project::build (v={{}})".format(self.version))
        """.format(v=version_str)
        })

        client.run("create . project/1.0@jgsogo/test --build=missing")

        # Check that everything is being built
        self.assertIn(
            "project/1.0@jgsogo/test: >>> PythonRequires11::build (v=1.0)",
            client.out)
        self.assertIn(
            "project/1.0@jgsogo/test: >>> PythonRequires0::build (v=1.0)",
            client.out)
        self.assertIn(
            "project/1.0@jgsogo/test: >>> PythonRequires22::build (v=1.0)",
            client.out)
        self.assertIn(
            "project/1.0@jgsogo/test: >>> PythonRequires1::build (v=1.0)",
            client.out)
        self.assertIn(
            "project/1.0@jgsogo/test: >>> PythonRequires2::build (v=1.0)",
            client.out)
        self.assertIn("project/1.0@jgsogo/test: >>> Project::build (v=1.0)",
                      client.out)

        # Check that all the graph is printed properly
        #   - requirements
        self.assertIn("    project/1.0@jgsogo/test from local cache - Cache",
                      client.out)
        #   - python requires
        self.assertIn("    python_requires11/1.0@jgsogo/test", client.out)
        self.assertIn("    python_requires0/1.0@jgsogo/test", client.out)
        self.assertIn("    python_requires22/1.0@jgsogo/test", client.out)
        self.assertIn("    python_requires1/1.0@jgsogo/test", client.out)
        self.assertIn("    python_requires2/1.0@jgsogo/test", client.out)
        #   - packages
        self.assertIn(
            "    project/1.0@jgsogo/test:5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9 - Build",
            client.out)

        #   - no mention to alias
        self.assertNotIn("alias", client.out)
        self.assertNotIn("alias2", client.out)
Example #13
0
 def test_with_no_user(self):
     test_server = TestServer()
     client = TestClient(servers={"default": test_server})
     client.run('user -p test', assert_error=True)
     self.assertIn("ERROR: User for remote 'default' is not defined. [Remote: default]",
                   client.out)
Example #14
0
    def test_json(self):
        def _compare_dicts(first_dict, second_dict):
            self.assertTrue(set(first_dict), set(second_dict))

        default_server = TestServer(users={"lasote": "mypass", "danimtb": "passpass"})
        other_server = TestServer()
        servers = OrderedDict()
        servers["default"] = default_server
        servers["other_server"] = other_server
        client = TestClient(servers=servers, users={"default": [("lasote", "mypass"),
                                                                ("danimtb", "passpass")],
                                                    "other_server": []})
        client.run("user --json user.json")
        content = client.load("user.json")
        info = json.loads(content)
        _compare_dicts({"error": False,
                        "remotes": [
                            {
                                "name": "default",
                                "authenticated": False,
                                "user_name": None
                            },
                            {
                                "name": "other_server",
                                "authenticated": False,
                                "user_name": None
                            }
                        ]}, info)

        client.run('user bad_user')
        client.run("user --json user.json")
        content = client.load("user.json")
        info = json.loads(content)
        _compare_dicts({"error": False,
                        "remotes": [
                            {
                                "name": "default",
                                "authenticated": False,
                                "user_name": "bad_user"
                            },
                            {
                                "name": "other_server",
                                "authenticated": False,
                                "user_name": None
                            }
                        ]}, info)

        client.run("user lasote")
        client.run("user --json user.json")
        content = client.load("user.json")
        info = json.loads(content)
        _compare_dicts({"error": False,
                        "remotes": [
                            {
                                "name": "default",
                                "authenticated": False,
                                "user_name": "lasote"
                            },
                            {
                                "name": "other_server",
                                "authenticated": False,
                                "user_name": None
                            }
                        ]}, info)

        client.run("user lasote -p mypass")
        client.run("user --json user.json")
        content = client.load("user.json")
        info = json.loads(content)
        _compare_dicts({"error": False,
                        "remotes": [
                            {
                                "name": "default",
                                "authenticated": True,
                                "user_name": "lasote"
                            },
                            {
                                "name": "other_server",
                                "authenticated": False,
                                "user_name": None
                            }
                        ]}, info)

        client.run("user danimtb -p passpass")
        client.run("user --json user.json")
        content = client.load("user.json")
        info = json.loads(content)
        _compare_dicts({"error": False,
                        "remotes": [
                            {
                                "name": "default",
                                "authenticated": True,
                                "user_name": "danimtb"
                            },
                            {
                                "name": "other_server",
                                "authenticated": False,
                                "user_name": None
                            }
                        ]}, info)

        client.run("user lasote -r other_server")
        client.run("user --json user.json")
        content = client.load("user.json")
        info = json.loads(content)
        _compare_dicts({"error": False,
                        "remotes": [
                            {
                                "name": "default",
                                "authenticated": True,
                                "user_name": "danimtb"
                            },
                            {
                                "name": "other_server",
                                "authenticated": False,
                                "user_name": "lasote"
                            }
                        ]}, info)

        client.run("user lasote -r default")
        client.run("user --json user.json")
        content = client.load("user.json")
        info = json.loads(content)
        _compare_dicts({"error": False,
                        "remotes": [
                            {
                                "name": "default",
                                "authenticated": False,
                                "user_name": "lasote"
                            },
                            {
                                "name": "other_server",
                                "authenticated": False,
                                "user_name": "lasote"
                            }
                        ]}, info)
 def setUp(self):
     self.t = TestClient()
     self.t.save({'conanfile.py': self.conanfile})
 def test_remote_monorepo_chdir(self):
     t = TestClient(path_with_spaces=False)
     t.run_command("svn co {} .".format(self.url))
     self._run_remote_test(t, os.path.join(t.current_folder, "lib1"), self.path_to_conanfile)
     self.assertIn("Repo origin deduced by 'auto':", t.out)
Example #17
0
 def setUp(self):
     self.client = TestClient()
     self.client.save({"conanfile.py": conanfile})
     self.client.run("export lasote/stable")
 def test_remote_root_folder(self):
     t = TestClient(path_with_spaces=False)
     t.run_command('git clone "{}" .'.format(self.url))
     self._run_remote_test(t, t.current_folder, self.path_to_conanfile)
Example #19
0
    def test_build_different_folders(self):
        conanfile = """
import os
from conans import ConanFile

class AConan(ConanFile):
    generators = "cmake"

    def build(self):
        self.output.warn("Build folder=>%s" % self.build_folder)
        self.output.warn("Src folder=>%s" % self.source_folder)
        self.output.warn("Package folder=>%s" % self.package_folder)
        assert(os.path.exists(self.build_folder))
        assert(os.path.exists(self.source_folder))
        # package_folder will be created manually or by the CMake helper when local invocation
        assert(not os.path.exists(self.package_folder))
"""

        client = TestClient()
        client.save({CONANFILE: conanfile})
        with client.chdir("build1"):
            client.run("install ..")
        # Try relative to cwd
        client.run("build . --build-folder build2 --install-folder build1 "
                   "--package-folder build1/pkg")
        self.assertIn(
            "Build folder=>%s" % os.path.join(client.current_folder, "build2"),
            client.out)
        self.assertIn(
            "Package folder=>%s" %
            os.path.join(client.current_folder, "build1", "pkg"), client.out)
        self.assertIn("Src folder=>%s" % client.current_folder, client.out)

        # Try default package folder
        client.run(
            "build conanfile.py --build-folder build1 --package-folder package1"
        )
        self.assertIn(
            "Build folder=>%s" % os.path.join(client.current_folder, "build1"),
            client.out)
        self.assertIn(
            "Package folder=>%s" %
            os.path.join(client.current_folder, "package"), client.out)
        self.assertIn("Src folder=>%s" % client.current_folder, client.out)

        # Try absolute package folder
        client.run("build . --build-folder build1 --package-folder '%s'" %
                   os.path.join(client.current_folder, "mypackage"))
        self.assertIn(
            "Build folder=>%s" % os.path.join(client.current_folder, "build1"),
            client.out)
        self.assertIn(
            "Package folder=>%s" %
            os.path.join(client.current_folder, "mypackage"), client.out)
        self.assertIn("Src folder=>%s" % client.current_folder, client.out)

        # Try absolute build and relative package
        conanfile_dir = client.current_folder
        bdir = os.path.join(client.current_folder, "other/mybuild")
        with client.chdir(bdir):
            client.run("install '%s'" % conanfile_dir)
        client.run(
            "build ./conanfile.py --build-folder '%s' --package-folder relpackage"
            % bdir)

        self.assertIn(
            "Build folder=>%s" %
            os.path.join(client.current_folder, "other/mybuild"), client.out)
        self.assertIn(
            "Package folder=>%s" %
            os.path.join(client.current_folder, "relpackage"), client.out)
        self.assertIn("Src folder=>%s" % client.current_folder, client.out)

        # Try different source
        with client.chdir("other/build"):
            client.run("install ../..")
        # src is not created automatically, it makes no sense
        client.run("build . --source-folder '%s' --build-folder other/build" %
                   os.path.join(client.current_folder, "mysrc"),
                   assert_error=True)

        mkdir(os.path.join(client.current_folder, "mysrc"))

        client.run("build . --source-folder '%s' --build-folder other/build" %
                   os.path.join(client.current_folder, "mysrc"))
        self.assertIn(
            "Build folder=>%s" %
            os.path.join(client.current_folder, "other", "build"), client.out)
        self.assertIn(
            "Package folder=>%s" %
            os.path.join(client.current_folder, "other", "build"), client.out)
        self.assertIn(
            "Src folder=>%s" % os.path.join(client.current_folder, "mysrc"),
            client.out)
def test_new_import():
    conanfile = GenConanfile(new_import=True)
    client = TestClient()
    client.save({"conanfile.py": conanfile})
    client.run("create . pkg/0.1@")
Example #21
0
    def complete_creation_reuse_test(self):
        client = TestClient(path_with_spaces=False)
        client.run("new myhello/1.0.0 --sources")
        conanfile_path = os.path.join(client.current_folder, "conanfile.py")
        replace_in_file(conanfile_path,
                        "{\"shared\": [True, False]}",
                        "{\"shared\": [True, False], \"fPIC\": [True, False]}",
                        output=client.out)
        replace_in_file(conanfile_path,
                        "\"shared=False\"",
                        "\"shared=False\", \"fPIC=True\"",
                        output=client.out)
        client.run("create . danimtb/testing")
        hellowrapper_include = """
#pragma once

void hellowrapper();
"""
        hellowrapper_impl = """
#include "hello.h"

#include "hellowrapper.h"

void hellowrapper(){
    hello();
}
"""
        makefile = """
include conanbuildinfo.mak

#----------------------------------------
#     Make variables for a sample App
#----------------------------------------

INCLUDE_DIRS = \
./include

CXX_SRCS = \
src/hellowrapper.cpp

CXX_OBJ_FILES = \
hellowrapper.o

STATIC_LIB_FILENAME = \
libhellowrapper.a

SHARED_LIB_FILENAME = \
libhellowrapper.so

CXXFLAGS += \
-fPIC

#----------------------------------------
#     Prepare flags from variables
#----------------------------------------

CFLAGS              += $(CONAN_CFLAGS)
CXXFLAGS            += $(CONAN_CXXFLAGS)
CPPFLAGS            += $(addprefix -I, $(INCLUDE_DIRS) $(CONAN_INCLUDE_DIRS))
CPPFLAGS            += $(addprefix -D, $(CONAN_DEFINES))
LDFLAGS             += $(addprefix -L, $(CONAN_LIB_DIRS))
LDLIBS              += $(addprefix -l, $(CONAN_LIBS))
SHAREDLINKFLAGS     += $(CONAN_SHAREDLINKFLAGS)

#----------------------------------------
#     Make Commands
#----------------------------------------

COMPILE_CXX_COMMAND         ?= \
	g++ -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@

CREATE_SHARED_LIB_COMMAND   ?= \
	g++ -shared $(CXX_OBJ_FILES) \
	$(CXXFLAGS) $(LDFLAGS) $(LDLIBS) $(SHAREDLINKFLAGS) \
	-o $(SHARED_LIB_FILENAME)

CREATE_STATIC_LIB_COMMAND   ?= \
	ar rcs $(STATIC_LIB_FILENAME) $(CXX_OBJ_FILES)


#----------------------------------------
#     Make Rules
#----------------------------------------

.PHONY                  :   static shared
static                  :   $(STATIC_LIB_FILENAME)
shared                  :   $(SHARED_LIB_FILENAME)

$(SHARED_LIB_FILENAME)  :   $(CXX_OBJ_FILES)
	$(CREATE_SHARED_LIB_COMMAND)

$(STATIC_LIB_FILENAME)  :   $(CXX_OBJ_FILES)
	$(CREATE_STATIC_LIB_COMMAND)

$(CXX_OBJ_FILES)        :   $(CXX_SRCS)
	$(COMPILE_CXX_COMMAND)
"""
        conanfile = """
from conans import ConanFile

class HelloWrapper(ConanFile):
    name = "hellowrapper"
    version = "1.0"
    settings = "os", "compiler", "build_type", "arch"
    requires = "myhello/1.0.0@danimtb/testing"
    generators = "make"
    exports_sources = "include/hellowrapper.h", "src/hellowrapper.cpp", "Makefile"
    options = {"shared": [True, False]}
    default_options = {"shared": False}

    def build(self):
        make_command = "make shared" if self.options.shared else "make static"
        self.run(make_command)

    def package(self):
        self.copy("*.h", dst="include", src="include")
        self.copy("*.so", dst="lib", keep_path=False)
        self.copy("*.a", dst="lib", keep_path=False)

    def package_info(self):
        self.cpp_info.libs = ["hellowrapper"]
"""
        client.save(
            {
                "include/hellowrapper.h": hellowrapper_include,
                "src/hellowrapper.cpp": hellowrapper_impl,
                "Makefile": makefile,
                "conanfile.py": conanfile
            },
            clean_first=True)
        client.run("create . danimtb/testing")
        # Test also shared
        client.run("create . danimtb/testing -o hellowrapper:shared=True")

        main = """
#include "hellowrapper.h"
int main()
{
     hellowrapper();
     return 0;
}
"""
        makefile = """
include conanbuildinfo.mak

#----------------------------------------
#     Make variables for a sample App
#----------------------------------------

CXX_SRCS = \
src/main.cpp

CXX_OBJ_FILES = \
main.o

EXE_FILENAME = \
main

CXXFLAGS += \
-fPIC

EXELINKFLAGS += \
-fPIE

#----------------------------------------
#     Prepare flags from variables
#----------------------------------------

CFLAGS              += $(CONAN_CFLAGS)
CXXFLAGS            += $(CONAN_CXXFLAGS)
CPPFLAGS            += $(addprefix -I, $(CONAN_INCLUDE_DIRS))
CPPFLAGS            += $(addprefix -D, $(CONAN_DEFINES))
LDFLAGS             += $(addprefix -L, $(CONAN_LIB_DIRS))
LDLIBS              += $(addprefix -l, $(CONAN_LIBS))
EXELINKFLAGS        += $(CONAN_EXELINKFLAGS)

#----------------------------------------
#     Make Commands
#----------------------------------------

COMPILE_CXX_COMMAND         ?= \
	g++ -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@

CREATE_EXE_COMMAND          ?= \
	g++ $(CXX_OBJ_FILES) \
	$(CXXFLAGS) $(LDFLAGS) $(LDLIBS) $(EXELINKFLAGS) \
	-o $(EXE_FILENAME)


#----------------------------------------
#     Make Rules
#----------------------------------------

.PHONY                  :   exe
exe                     :   $(EXE_FILENAME)

$(EXE_FILENAME)         :   $(CXX_OBJ_FILES)
	$(CREATE_EXE_COMMAND)

$(CXX_OBJ_FILES)        :   $(CXX_SRCS)
	$(COMPILE_CXX_COMMAND)
"""
        conanfile_txt = """
[requires]
hellowrapper/1.0@danimtb/testing

[generators]
make
"""
        client.save(
            {
                "src/main.cpp": main,
                "Makefile": makefile,
                "conanfile.txt": conanfile_txt
            },
            clean_first=True)
        with chdir(client.current_folder):
            client.run("install .")
            client.runner("make exe")
            client.runner("./main")
            self.assertIn("Hello World Release!", client.out)

            # Test it also builds with shared lib
            client.run("install . -o hellowrapper:shared=True")
            client.runner("rm main main.o")
            client.runner("make exe")
            client.runner("ldd main")
            self.assertIn("libhellowrapper.so", client.out)
Example #22
0
 def setUp(self):
     test_server = TestServer([],  # write permissions
                              users={"lasote": "mypass"})  # exported users and passwords
     self.servers = {"default": test_server}
     self.client = TestClient(servers=self.servers, users={"default": [("lasote", "mypass")]})
Example #23
0
    def new_ci_test_partial(self):
        client = TestClient()
        root = client.current_folder
        error = client.run('new MyPackage/1.3@myuser/testing -cis',
                           ignore_error=True)
        self.assertTrue(error)

        client.run('new MyPackage/1.3@myuser/testing -cilg')
        self.assertTrue(os.path.exists(os.path.join(root, "build.py")))
        self.assertTrue(os.path.exists(os.path.join(root, ".travis.yml")))
        self.assertTrue(
            os.path.exists(os.path.join(root, ".travis/install.sh")))
        self.assertTrue(os.path.exists(os.path.join(root, ".travis/run.sh")))
        self.assertFalse(os.path.exists(os.path.join(root, "appveyor.yml")))
        self.assertFalse(os.path.exists(os.path.join(root, ".gitlab-ci.yml")))

        client = TestClient()
        root = client.current_folder
        client.run('new MyPackage/1.3@myuser/testing -ciw')
        self.assertTrue(os.path.exists(os.path.join(root, "build.py")))
        self.assertFalse(os.path.exists(os.path.join(root, ".travis.yml")))
        self.assertFalse(
            os.path.exists(os.path.join(root, ".travis/install.sh")))
        self.assertFalse(os.path.exists(os.path.join(root, ".travis/run.sh")))
        self.assertTrue(os.path.exists(os.path.join(root, "appveyor.yml")))
        self.assertFalse(os.path.exists(os.path.join(root, ".gitlab-ci.yml")))

        client = TestClient()
        root = client.current_folder
        client.run('new MyPackage/1.3@myuser/testing -cio')
        self.assertTrue(os.path.exists(os.path.join(root, "build.py")))
        self.assertTrue(os.path.exists(os.path.join(root, ".travis.yml")))
        self.assertTrue(
            os.path.exists(os.path.join(root, ".travis/install.sh")))
        self.assertTrue(os.path.exists(os.path.join(root, ".travis/run.sh")))
        self.assertFalse(os.path.exists(os.path.join(root, "appveyor.yml")))
        self.assertFalse(os.path.exists(os.path.join(root, ".gitlab-ci.yml")))

        client = TestClient()
        root = client.current_folder
        client.run('new MyPackage/1.3@myuser/testing -gi')
        self.assertTrue(os.path.exists(os.path.join(root, ".gitignore")))

        client = TestClient()
        root = client.current_folder
        client.run('new MyPackage/1.3@myuser/testing -ciglg')
        self.assertTrue(os.path.exists(os.path.join(root, "build.py")))
        self.assertTrue(os.path.exists(os.path.join(root, ".gitlab-ci.yml")))
        self.assertFalse(os.path.exists(os.path.join(root, ".travis.yml")))
        self.assertFalse(
            os.path.exists(os.path.join(root, ".travis/install.sh")))
        self.assertFalse(os.path.exists(os.path.join(root, ".travis/run.sh")))
        self.assertFalse(os.path.exists(os.path.join(root, "appveyor.yml")))

        client = TestClient()
        root = client.current_folder
        client.run('new MyPackage/1.3@myuser/testing -ciglc')
        self.assertTrue(os.path.exists(os.path.join(root, "build.py")))
        self.assertTrue(os.path.exists(os.path.join(root, ".gitlab-ci.yml")))
        self.assertFalse(os.path.exists(os.path.join(root, ".travis.yml")))
        self.assertFalse(
            os.path.exists(os.path.join(root, ".travis/install.sh")))
        self.assertFalse(os.path.exists(os.path.join(root, ".travis/run.sh")))
        self.assertFalse(os.path.exists(os.path.join(root, "appveyor.yml")))
Example #24
0
    def setUpClass(cls):
        libZ_ref = ConanFileReference.loads("libZ/version")
        libH2_ref = ConanFileReference.loads("header2/version")
        libH_ref = ConanFileReference.loads("header/version")
        libA_ref = ConanFileReference.loads("libA/version")
        libB_ref = ConanFileReference.loads("libB/version")
        libC_ref = ConanFileReference.loads("libC/version")
        libD_ref = ConanFileReference.loads("libD/version")

        t = TestClient(path_with_spaces=False)
        cls._cache_folder = t.cache_folder
        t.save({
            'libZ/conanfile.py': cls.conanfile.render(
                ref=libZ_ref,
                libs_extra=["Z2"],
                libs_system=["system_assumed"],
                system_libs=["system_lib"],
                frameworks=["Carbon"]),
            'libH2/conanfile.py': cls.conanfile_headeronly.render(
                ref=libH2_ref,
                libs_system=["header2_system_assumed"],
                system_libs=["header2_system_lib"],
                frameworks=["Security"]),
            'libH/conanfile.py': cls.conanfile_headeronly.render(
                ref=libH_ref,
                requires=[libH2_ref, libZ_ref],
                libs_system=["header_system_assumed"],
                system_libs=["header_system_lib"],
                frameworks=["CoreAudio"]),
            'libA/conanfile.py': cls.conanfile.render(
                ref=libA_ref,
                requires=[libH_ref],
                libs_extra=["A2"],
                libs_system=["system_assumed"],
                system_libs=["system_lib"],
                frameworks=["Carbon"]),
            'libB/conanfile.py': cls.conanfile.render(
                ref=libB_ref,
                requires=[libA_ref],
                libs_extra=["B2"],
                libs_system=["system_assumed"],
                system_libs=["system_lib"],
                frameworks=["Carbon"]),
            'libC/conanfile.py': cls.conanfile.render(
                ref=libC_ref,
                requires=[libA_ref],
                libs_extra=["C2"],
                libs_system=["system_assumed"],
                system_libs=["system_lib"],
                frameworks=["Carbon"]),
            'libD/conanfile.py': cls.conanfile.render(
                ref=libD_ref,
                requires=[libB_ref, libC_ref],
                libs_extra=["D2"],
                libs_system=["system_assumed"],
                system_libs=["system_lib"],
                frameworks=["Carbon"]),
        })

        # Create all of them
        t.run("create libZ")
        t.run("create libH2")
        t.run("create libH")
        t.run("create libA")
        t.run("create libB")
        t.run("create libC")
        t.run("create libD")
Example #25
0
    def test_package_info_components(self):
        dep = textwrap.dedent("""
            import os
            from conans import ConanFile

            class Dep(ConanFile):

                def package_info(self):
                    self.cpp_info.components["dep1"].libs.append("libdep1")
                    self.cpp_info.components["dep1"].defines.append("definedep1")
                    self.cpp_info.components["dep2"].libs.append("libdep2")
                    os.mkdir(os.path.join(self.package_folder, "include"))
                    os.mkdir(os.path.join(self.package_folder, "includedep2"))
                    self.cpp_info.components["dep2"].includedirs.append("includedep2")
                """)
        intermediate = textwrap.dedent("""
            import os
            from conans import ConanFile

            class Intermediate(ConanFile):
                requires = "dep/1.0@us/ch"

                def package_info(self):
                    self.cpp_info.components["int1"].requires = ["dep::dep"]  # To avoid exception
                    self.cpp_info.components["int1"].libs.append("libint1")
                    self.cpp_info.components["int1"].defines.append("defint1")
                    os.mkdir(os.path.join(self.package_folder, "include"))
                    os.mkdir(os.path.join(self.package_folder, "includeint1"))
                    self.cpp_info.components["int1"].includedirs.append("includeint1")
                    self.cpp_info.components["int2"].libs.append("libint2")
                    self.cpp_info.components["int2"].defines.append("defint2")
                    os.mkdir(os.path.join(self.package_folder, "includeint2"))
                    self.cpp_info.components["int2"].includedirs.append("includeint2")
                """)
        consumer = textwrap.dedent("""
            import os
            from conans import ConanFile

            class Consumer(ConanFile):
                requires = "intermediate/1.0@us/ch"

                def build(self):
                    self.output.info("deps_cpp_info.libs: %s" % list(self.deps_cpp_info.libs))
                    self.output.info("deps_cpp_info.defines: %s" % list(self.deps_cpp_info.defines))
                    self.output.info("deps_cpp_info.include_paths: %s" %
                        [os.path.basename(value) for value in self.deps_cpp_info.include_paths])
                    for dep_key, dep_value in self.deps_cpp_info.dependencies:
                        self.output.info("%s.libs: %s" % (dep_key, list(dep_value.libs)))
                        self.output.info("%s.defines: %s" % (dep_key, list(dep_value.defines)))
                        self.output.info("%s.include_paths: %s" % (dep_key,
                                         [os.path.basename(value) for value in
                                         dep_value.include_paths]))
                """)

        client = TestClient()
        client.save({
            "conanfile_dep.py": dep,
            "conanfile_intermediate.py": intermediate,
            "conanfile_consumer.py": consumer
        })
        client.run("export conanfile_dep.py dep/1.0@us/ch")
        client.run("export conanfile_intermediate.py intermediate/1.0@us/ch")
        client.run(
            "create conanfile_consumer.py consumer/1.0@us/ch --build missing")

        self.assertIn(
            "deps_cpp_info.libs: ['libint1', 'libint2', 'libdep1', 'libdep2']",
            client.out)
        self.assertIn(
            "deps_cpp_info.defines: ['definedep1', 'defint1', 'defint2']",
            client.out)
        self.assertIn(
            "deps_cpp_info.include_paths: ['include', 'includeint1', 'includeint2', "
            "'include', 'includedep2']", client.out)

        self.assertIn("intermediate.libs: ['libint1', 'libint2']", client.out)
        self.assertIn("intermediate.defines: ['defint1', 'defint2']",
                      client.out)
        self.assertIn(
            "intermediate.include_paths: ['include', 'includeint1', 'includeint2']",
            client.out)

        self.assertIn("dep.libs: ['libdep1', 'libdep2']", client.out)
        self.assertIn("dep.defines: ['definedep1']", client.out)
        self.assertIn("dep.include_paths: ['include', 'includedep2']",
                      client.out)
Example #26
0
    def test_update_settings(self):
        """ This test is to validate that after adding a new settings, that allows a None
    value, this None value does not modify exisisting packages SHAs
    """
        file_content = '''
from conans import ConanFile

class ConanFileToolsTest(ConanFile):
    name = "test"
    version = "1.9"
    settings = "os", "compiler", "arch"

    def source(self):
        self.output.warn("Sourcing...")

    def build(self):
        self.output.warn("Building...")
    '''
        prev_settings = """
os: [Windows, Linux, Macos, Android, FreeBSD, SunOS]
arch: [x86, x86_64, armv6, armv7, armv7hf, armv8, sparc, sparcv9]
os_build: [Windows, Linux, Macos, Android, FreeBSD, SunOS]
arch_build: [x86, x86_64, armv6, armv7, armv7hf, armv8, sparc, sparcv9]

compiler:
    sun-cc:
        version: ["5.10", "5.11", "5.12", "5.13", "5.14"]
        libcxx: [libCstd, libstdcxx libstlport, libstdc++]
    gcc:
        version: ["4.4", "4.5", "4.6", "4.7", "4.8", "4.9", "5.1", "5.2", "5.3", "5.4", "6.1", "6.2", "6.3"]
        libcxx: [libstdc++, libstdc++11]
    Visual Studio:
        runtime: [None, MD, MT, MTd, MDd]
        version: ["8", "9", "10", "11", "12", "14"]
    clang:
        version: ["3.3", "3.4", "3.5", "3.6", "3.7", "3.8"]
        libcxx: [libstdc++, libstdc++11, libc++]
    apple-clang:
        version: ["5.0", "5.1", "6.0", "6.1", "7.0", "7.1", "7.2", "7.3", "8.0", "8.1"]
        libcxx: [libstdc++, libc++]

"""
        files = {"conanfile.py": file_content}
        client = TestClient()
        client.save(files)
        client.run("export . lasote/testing")
        save(client.paths.settings_path, prev_settings)
        client.client_cache.default_profile  # Generate the default
        conf = load(client.client_cache.default_profile_path)
        conf = conf.replace("build_type=Release", "")
        self.assertNotIn("build_type", conf)
        save(client.client_cache.default_profile_path, conf)

        client.run(
            "install test/1.9@lasote/testing --build -s arch=x86_64 -s compiler=gcc "
            "-s compiler.version=4.9 -s os=Windows -s compiler.libcxx=libstdc++"
        )
        self.assertIn("390146894f59dda18c902ee25e649ef590140732",
                      client.user_io.out)

        # Now the new one
        files = {
            "conanfile.py": file_content.replace('"arch"',
                                                 '"arch", "build_type"')
        }
        client = TestClient()
        client.save(files)
        client.run("export . lasote/testing")

        client.run(
            "install test/1.9@lasote/testing --build -s arch=x86_64 -s compiler=gcc "
            "-s compiler.version=4.9 -s os=Windows -s build_type=None -s compiler.libcxx=libstdc++"
        )
        self.assertIn("build_type", load(client.paths.settings_path))
        self.assertIn("390146894f59dda18c902ee25e649ef590140732",
                      client.user_io.out)
Example #27
0
    def test_package_requires_in_components_requires(self):
        client = TestClient()
        client.save({
            "conanfile1.py": GenConanfile("dep1", "0.1"),
            "conanfile2.py": GenConanfile("dep2", "0.1")
        })
        client.run("create conanfile1.py")
        client.run("create conanfile2.py")

        conanfile = GenConanfile("consumer", "0.1") \
            .with_requirement("dep1/0.1") \
            .with_requirement("dep2/0.1") \
            .with_package_info(cpp_info={"components": {"kk": {"requires": []}}},
                               env_info={})
        client.save({"conanfile.py": conanfile})
        client.run("create conanfile.py", assert_error=True)
        self.assertIn(
            "consumer/0.1 package_info(): Package require 'dep1' not used in "
            "components requires", client.out)

        conanfile = GenConanfile("consumer", "0.1") \
            .with_requirement("dep1/0.1") \
            .with_requirement("dep2/0.1") \
            .with_package_info(cpp_info={"components": {"kk": {"requires": ["dep1::dep1"]}}},
                               env_info={})
        client.save({"conanfile.py": conanfile})
        client.run("create conanfile.py", assert_error=True)
        self.assertIn(
            "consumer/0.1 package_info(): Package require 'dep2' not used in components "
            "requires", client.out)

        conanfile = GenConanfile("consumer", "0.1") \
            .with_requirement("dep1/0.1") \
            .with_requirement("dep2/0.1") \
            .with_package_info(cpp_info={"components": {"kk": {"requires": ["dep1::dep1"]},
                                                        "kkk": {"requires": ["kk"]}}},
                               env_info={})
        client.save({"conanfile.py": conanfile})
        client.run("create conanfile.py", assert_error=True)
        self.assertIn(
            "consumer/0.1 package_info(): Package require 'dep2' not used in components "
            "requires", client.out)

        conanfile = GenConanfile("consumer", "0.1") \
            .with_requirement("dep1/0.1") \
            .with_requirement("dep2/0.1") \
            .with_package_info(cpp_info={"components": {"kk": {"requires": []},
                                                        "kkk": {"requires": ["kk"]}}},
                               env_info={})
        client.save({"conanfile.py": conanfile})
        client.run("create conanfile.py", assert_error=True)
        self.assertIn(
            "consumer/0.1 package_info(): Package require 'dep1' not used in components "
            "requires", client.out)

        conanfile = GenConanfile("consumer", "0.1") \
            .with_requirement("dep1/0.1") \
            .with_requirement("dep2/0.1") \
            .with_package_info(cpp_info={"components": {"kk": {"requires": ["dep2::comp"]},
                                                        "kkk": {"requires": ["dep3::dep3"]}}},
                               env_info={})
        client.save({"conanfile.py": conanfile})
        client.run("create conanfile.py", assert_error=True)
        self.assertIn(
            "consumer/0.1 package_info(): Package require 'dep1' not used in components "
            "requires", client.out)

        conanfile = GenConanfile("consumer", "0.1") \
            .with_requirement("dep2/0.1") \
            .with_package_info(cpp_info={"components": {"kk": {"requires": ["dep2::comp"]},
                                                        "kkk": {"requires": ["dep3::dep3"]}}},
                               env_info={})
        client.save({"conanfile.py": conanfile})
        client.run("create conanfile.py", assert_error=True)
        self.assertIn(
            "consumer/0.1 package_info(): Package require 'dep3' declared in components "
            "requires but not defined as a recipe requirement", client.out)

        conanfile = GenConanfile("consumer", "0.1") \
            .with_package_info(cpp_info={"components": {"kk": {"requires": ["dep2::comp"]}}},
                               env_info={})
        client.save({"conanfile.py": conanfile})
        client.run("create conanfile.py", assert_error=True)
        self.assertIn(
            "consumer/0.1 package_info(): Package require 'dep2' declared in components "
            "requires but not defined as a recipe requirement", client.out)

        conanfile = GenConanfile("consumer", "0.1") \
            .with_requirement("dep1/0.1") \
            .with_requirement("dep2/0.1") \
            .with_package_info(cpp_info={"components": {"kk": {"requires": ["dep2::comp"]},
                                                        "kkk": {"requires": ["dep1::dep1"]}}},
                               env_info={})
        client.save({"conanfile.py": conanfile})
        client.run("create conanfile.py")  # Correct usage
Example #28
0
def test_cmaketoolchain_path_find_package_real_config(settings, find_root_path_modes):
    client = TestClient()

    conanfile = textwrap.dedent("""
        from conans import ConanFile
        from conan.tools.cmake import CMake
        import os
        class TestConan(ConanFile):
            settings = "os", "compiler", "build_type", "arch"
            exports_sources = "*"
            generators = "CMakeToolchain"

            def layout(self):
                pass

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

            def package(self):
                cmake = CMake(self)
                cmake.install()

            def package_info(self):
                self.cpp_info.builddirs.append(os.path.join("hello", "cmake"))
        """)
    cmake = textwrap.dedent("""
        cmake_minimum_required(VERSION 3.15)
        project(MyHello NONE)

        add_library(hello INTERFACE)
        install(TARGETS hello EXPORT helloConfig)
        export(TARGETS hello
            NAMESPACE hello::
            FILE "${CMAKE_CURRENT_BINARY_DIR}/helloConfig.cmake"
        )
        install(EXPORT helloConfig
            DESTINATION "${CMAKE_INSTALL_PREFIX}/hello/cmake"
            NAMESPACE hello::
        )
        """)
    client.save({"conanfile.py": conanfile, "CMakeLists.txt": cmake})
    client.run("create . hello/0.1@ -pr:b default {}".format(settings))

    consumer = textwrap.dedent("""
        cmake_minimum_required(VERSION 3.15)
        project(MyHello NONE)

        find_package(hello REQUIRED)
        """)

    client.save({"CMakeLists.txt": consumer}, clean_first=True)
    client.run("install hello/0.1@ -g CMakeToolchain -pr:b default {}".format(settings))
    with client.chdir("build"):
        client.run_command(_cmake_command_toolchain(find_root_path_modes))
    # If it didn't fail, it found the helloConfig.cmake
    assert "Conan: Target declared" not in client.out

    # If using the CMakeDeps generator, the in-package .cmake will be ignored
    client.run("install hello/0.1@ -g CMakeToolchain -g CMakeDeps -pr:b default {}".format(settings))
    with client.chdir("build2"):  # A clean folder, not the previous one, CMake cache doesnt affect
        client.run_command(_cmake_command_toolchain(find_root_path_modes))
    assert "Conan: Target declared 'hello::hello'" in client.out
Example #29
0
    def reuse_test(self):
        self._export_upload("Hello0", "0.1")
        self._export_upload("Hello1",
                            "0.1",
                            deps=[("Hello0/0.1@lasote/stable", "private")],
                            static=False)

        client = TestClient(servers=self.servers,
                            users={"default": [("lasote", "mypass")]})
        files3 = cpp_hello_conan_files("Hello3", "0.1",
                                       ["Hello1/0.1@lasote/stable"])
        client.save(files3)

        client.run('install . --build missing')
        client.run('build .')

        # assert Hello3 only depends on Hello2, and Hello1
        build_info_cmake = load(
            os.path.join(client.current_folder, BUILD_INFO_CMAKE))
        # Ensure it does not depend on Hello0 to build, as private in dlls
        self.assertNotIn("Hello0", repr(build_info_cmake))

        command = os.sep.join([".", "bin", "say_hello"])
        client.runner(command, cwd=client.current_folder)
        self.assertEqual(['Hello Hello3', 'Hello Hello1', 'Hello Hello0'],
                         str(client.user_io.out).splitlines()[-3:])

        conan_info = ConanInfo.loads(
            load(os.path.join(client.current_folder, CONANINFO)))
        self.assertEqual("language=0\nstatic=True", conan_info.options.dumps())

        # Try to upload and reuse the binaries
        client.run("upload Hello1/0.1@lasote/stable --all")
        self.assertEqual(str(client.user_io.out).count("Uploading package"), 1)

        client2 = TestClient(servers=self.servers,
                             users={"default": [("lasote", "mypass")]})
        client2.save(files3)

        client2.run("install .")
        self.assertNotIn("Package installed in Hello0/0.1",
                         client2.user_io.out)
        self.assertNotIn("Building", client2.user_io.out)
        client2.run("build .")

        self.assertNotIn("libhello0.a", client2.user_io.out)
        self.assertNotIn("libhello1.a", client2.user_io.out)
        self.assertNotIn("libhello3.a", client2.user_io.out)
        client2.runner(command, cwd=client2.current_folder)

        self.assertEqual(['Hello Hello3', 'Hello Hello1', 'Hello Hello0'],
                         str(client2.user_io.out).splitlines()[-3:])

        # Issue 79, fixing private deps from current project
        files3 = cpp_hello_conan_files(
            "Hello3",
            "0.2", [
                "Hello1/0.1@lasote/stable",
                ("Hello0/0.1@lasote/stable", "private")
            ],
            language=1)

        client2.save(files3, clean_first=True)
        client2.run('install . -o language=1 --build missing')
        client2.run('build .')
        self.assertNotIn("libhello0.a", client2.user_io.out)
        self.assertNotIn("libhello1.a", client2.user_io.out)
        self.assertNotIn("libhello3.a", client2.user_io.out)
        client2.runner(command, cwd=client2.current_folder)
        self.assertEqual(
            ['Hola Hello3', 'Hola Hello1', 'Hola Hello0', 'Hola Hello0'],
            str(client2.user_io.out).splitlines()[-4:])
Example #30
0
    def recipe_revision_mode_test(self):
        clienta = TestClient()
        clienta.run(
            "config set general.default_package_id_mode=recipe_revision_mode")
        conanfilea = dedent("""
            from conans import ConanFile
            from conans.tools import save
            import uuid, os
            class Pkg(ConanFile):
                def package(self):
                    save(os.path.join(self.package_folder, "file.txt"),
                         str(uuid.uuid1()))
            """)
        clienta.save({"conanfile.py": conanfilea})
        clienta.run("create . liba/0.1@user/testing")

        clientb = TestClient(cache_folder=clienta.cache_folder)
        clientb.save({
            "conanfile.py":
            str(
                TestConanFile("libb",
                              "0.1",
                              requires=["liba/0.1@user/testing"]))
        })
        clientb.run("create . user/testing")

        clientc = TestClient(cache_folder=clienta.cache_folder)
        clientc.save({
            "conanfile.py":
            str(
                TestConanFile("libc",
                              "0.1",
                              requires=["libb/0.1@user/testing"]))
        })
        clientc.run("install . user/testing")

        # Do a minor change to the recipe, it will change the recipe revision
        clienta.save({"conanfile.py": conanfilea + "# comment"})
        clienta.run("create . liba/0.1@user/testing")

        clientc.run("install . user/testing", assert_error=True)
        self.assertIn(
            "ERROR: Missing prebuilt package for 'libb/0.1@user/testing'",
            clientc.out)
        # Building b with the new recipe revision of liba works
        clientc.run("install . user/testing --build=libb")

        # Now change only the package revision of liba
        clienta.run("create . liba/0.1@user/testing")
        clientc.run("install . user/testing")
        clientc.run(
            "config set general.default_package_id_mode=package_revision_mode")
        clientc.run("install . user/testing", assert_error=True)
        self.assertIn(
            "ERROR: Missing prebuilt package for 'libb/0.1@user/testing'",
            clientc.out)
        clientc.run("install . user/testing --build=libb")
        clientc.run("info . --build-order=ALL")

        clienta.run("create . liba/0.1@user/testing")
        clientc.run("install . user/testing", assert_error=True)
        self.assertIn(
            "ERROR: Missing prebuilt package for 'libb/0.1@user/testing'",
            clientc.out)

        clienta.run("create . liba/0.1@user/testing")
        clientc.run("info . --build-order=ALL")