def test_txt(self):
        base = '''[requires]
lib/0.1@user/channel
'''
        extension = '''[requires]
lib/0.1@user/channel
otherlib/0.2@user/channel

[options]
otherlib:otherlib_option = 1
'''
        files = {"conanfile.txt": base,
                 "conanfile_dev.txt": extension}

        client = TestClient(self.base_folder)
        client.save(files)
        client.run("install . --build")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("lib/0.1@user/channel", conaninfo)
        self.assertNotIn("otherlib/0.2@user/channel", conaninfo)
        self.assertNotIn("otherlib:otherlib_option=1", conaninfo)

        client.run("install conanfile_dev.txt --build")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("lib/0.1@user/channel", conaninfo)
        self.assertIn("otherlib/0.2@user/channel", conaninfo)
        self.assertIn("otherlib:otherlib_option=1", conaninfo)
Beispiel #2
0
    def export_test(self):
        if platform.system() == "Windows":
            return

        lib_name = "libtest.so.2"
        lib_contents = "TestLib"
        link_name = "libtest.so"

        client = TestClient()
        client.save({"conanfile.py": conanfile,
                     "conanfile.txt": test_conanfile,
                     lib_name: lib_contents})

        pre_export_link = os.path.join(client.current_folder, link_name)
        os.symlink(lib_name, pre_export_link)

        client.run("export lasote/stable")
        client.run("install --build -f=conanfile.txt")
        conan_ref = ConanFileReference.loads("Hello/0.1@lasote/stable")
        package_ref = PackageReference(conan_ref,
                                       "5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")

        for folder in [client.paths.export(conan_ref), client.paths.source(conan_ref),
                       client.paths.build(package_ref), client.paths.package(package_ref)]:
            exported_lib = os.path.join(folder, lib_name)
            exported_link = os.path.join(folder, link_name)
            self.assertEqual(os.readlink(exported_link), lib_name)

            self.assertEqual(load(exported_lib), load(exported_link))
            self.assertTrue(os.path.islink(exported_link))

        self._check(client, package_ref)
Beispiel #3
0
    def reuse_test(self):
        conan_reference = ConanFileReference.loads("Hello0/0.1@lasote/stable")
        files = cpp_hello_conan_files("Hello0", "0.1", build=False)

        client = TestClient(servers=self.servers, users={"default": [("lasote", "mypass")]})
        client.save(files)
        client.run("export lasote/stable")
        client.run("upload %s" % str(conan_reference))

        gen_reference = ConanFileReference.loads("MyCustomGen/0.2@lasote/stable")
        files = {CONANFILE: generator}
        client = TestClient(servers=self.servers, users={"default": [("lasote", "mypass")]})
        client.save(files)
        client.run("export lasote/stable")
        client.run("upload %s" % str(gen_reference))

        # Test local, no retrieval
        files = {CONANFILE_TXT: consumer}
        client.save(files, clean_first=True)
        client.run("install --build")
        generated = load(os.path.join(client.current_folder, "customfile.gen"))
        self.assertEqual(generated, "My custom generator content")

        # Test retrieval from remote
        client = TestClient(servers=self.servers, users={"default": [("lasote", "mypass")]})
        files = {CONANFILE_TXT: consumer}
        client.save(files)
        client.run("install --build")

        generated = load(os.path.join(client.current_folder, "customfile.gen"))
        self.assertEqual(generated, "My custom generator content")
Beispiel #4
0
    def test_basic(self):
        client = TestClient()
        conanfile = """
from conans import ConanFile
class TestConan(ConanFile):
    name = "Hello"
    version = "0.1"
    settings = "os"
"""
        client.save({CONANFILE: conanfile})
        client.run("export lasote/stable")

        client.save({"include/header.h": "//Windows header"}, clean_first=True)
        client.run("package_files Hello/0.1@lasote/stable -s os=Windows")
        conan_ref = ConanFileReference.loads("Hello/0.1@lasote/stable")
        win_package_ref = PackageReference(conan_ref, "3475bd55b91ae904ac96fde0f106a136ab951a5e")
        package_folder = client.client_cache.package(win_package_ref)
        self.assertEqual(load(os.path.join(package_folder, "include/header.h")),
                         "//Windows header")
        self._consume(client, "-s os=Windows")
        self.assertIn("Hello/0.1@lasote/stable:3475bd55b91ae904ac96fde0f106a136ab951a5e",
                      client.user_io.out)

        # Now repeat
        client.save({"include/header.h": "//Windows header2"}, clean_first=True)
        err = client.run("package_files Hello/0.1@lasote/stable -s os=Windows", ignore_error=True)
        self.assertTrue(err)
        self.assertIn("Package already exists. Please use --force, -f to overwrite it",
                      client.user_io.out)
        client.run("package_files Hello/0.1@lasote/stable -s os=Windows -f")
        self.assertEqual(load(os.path.join(package_folder, "include/header.h")),
                         "//Windows header2")
    def test_override(self):

        files = cpp_hello_conan_files(name="VisualBuild",
                                      version="0.1", build=False, deps=["MinGWBuild/0.1@lasote/testing"])
        self._patch_build_to_print_compiler(files)
        self.client.save(files)
        self.client.run("export . lasote/testing")
        self.client.run("install VisualBuild/0.1@lasote/testing --build missing -s compiler='Visual Studio' "
                        "-s compiler.version=14 -s compiler.runtime=MD "
                        "-s MinGWBuild:compiler='gcc' -s MinGWBuild:compiler.libcxx='libstdc++' "
                        "-s MinGWBuild:compiler.version=4.8")

        self.assertIn("COMPILER=> MinGWBuild gcc", self.client.user_io.out)
        self.assertIn("COMPILER=> VisualBuild Visual Studio", self.client.user_io.out)

        # CHECK CONANINFO FILE
        packs_dir = self.client.paths.packages(ConanFileReference.loads("MinGWBuild/0.1@lasote/testing"))
        pack_dir = os.path.join(packs_dir, os.listdir(packs_dir)[0])
        conaninfo = load(os.path.join(pack_dir, CONANINFO))
        self.assertIn("compiler=gcc", conaninfo)

        # CHECK CONANINFO FILE
        packs_dir = self.client.paths.packages(ConanFileReference.loads("VisualBuild/0.1@lasote/testing"))
        pack_dir = os.path.join(packs_dir, os.listdir(packs_dir)[0])
        conaninfo = load(os.path.join(pack_dir, CONANINFO))
        self.assertIn("compiler=Visual Studio", conaninfo)
        self.assertIn("compiler.version=14", conaninfo)
Beispiel #6
0
    def test_package_folder(self):
        # https://github.com/conan-io/conan/issues/2350
        conanfile = """from conans import ConanFile
class HelloPythonConan(ConanFile):
    settings = "os"
    def package(self):
        self.output.info("PACKAGE NOT CALLED")
        raise Exception("PACKAGE NOT CALLED")
"""
        client = TestClient()
        client.save({CONANFILE: conanfile,
                     "pkg/myfile.h": "",
                     "profile": "[settings]\nos=Windows"})

        client.run("export-pkg . Hello/0.1@lasote/stable -pf=pkg -pr=profile")
        self.assertNotIn("PACKAGE NOT CALLED", client.out)
        self.assertIn("Hello/0.1@lasote/stable: Copied 1 '.h' file: myfile.h", client.out)
        ref = ConanFileReference.loads("Hello/0.1@lasote/stable")
        pkg_folder = client.client_cache.packages(ref)
        folders = os.listdir(pkg_folder)
        pkg_folder = os.path.join(pkg_folder, folders[0])
        conaninfo = load(os.path.join(pkg_folder, "conaninfo.txt"))
        self.assertEqual(2, conaninfo.count("os=Windows"))
        manifest = load(os.path.join(pkg_folder, "conanmanifest.txt"))
        self.assertIn("conaninfo.txt: f395060da1ffdeb934be8b62e4bd8a3a", manifest)
        self.assertIn("myfile.h: d41d8cd98f00b204e9800998ecf8427e", manifest)
Beispiel #7
0
    def test_build_source_folders(self):
        client = TestClient()
        conanfile = """from conans import ConanFile
class TestConan(ConanFile):
    settings = "os"

    def package(self):
        self.copy("*.h", src="include", dst="inc")
        self.copy("*.lib", src="lib", dst="lib")
"""
        client.save({CONANFILE: conanfile,
                     "src/include/header.h": "//Windows header",
                     "src/include/header.txt": "",
                     "build/libs/what": "",
                     "build/lib/hello.lib": "My Lib",
                     "build/lib/bye.txt": ""})
        client.run("export-pkg . Hello/0.1@lasote/stable -s os=Windows --build-folder=build "
                   "--source-folder=src")
        conan_ref = ConanFileReference.loads("Hello/0.1@lasote/stable")
        package_ref = PackageReference(conan_ref, "3475bd55b91ae904ac96fde0f106a136ab951a5e")
        package_folder = client.client_cache.package(package_ref)
        inc = os.path.join(package_folder, "inc")
        self.assertEqual(os.listdir(inc), ["header.h"])
        self.assertEqual(load(os.path.join(inc, "header.h")), "//Windows header")
        lib = os.path.join(package_folder, "lib")
        self.assertEqual(os.listdir(lib), ["hello.lib"])
        self.assertEqual(load(os.path.join(lib, "hello.lib")), "My Lib")
Beispiel #8
0
    def install_profile_settings_test(self):
        files = cpp_hello_conan_files("Hello0", "0.1", build=False)
        files["conanfile.py"] = files["conanfile.py"].replace("generators =", "generators = \"txt\",")

        # Create a profile and use it
        profile_settings = {"compiler": "Visual Studio",
                            "compiler.version": "12",
                            "compiler.runtime": "MD",
                            "arch": "x86"}
        self._create_profile("vs_12_86", profile_settings)

        self.client.save(files)
        self.client.run("export lasote/stable")
        self.client.run("install --build missing -pr vs_12_86")
        info = load(os.path.join(self.client.current_folder, "conaninfo.txt"))
        for setting, value in profile_settings.items():
            self.assertIn("%s=%s" % (setting, value), info)

        # Try to override some settings in install command
        self.client.run("install --build missing -pr vs_12_86 -s compiler.version=14")
        info = load(os.path.join(self.client.current_folder, "conaninfo.txt"))
        for setting, value in profile_settings.items():
            if setting != "compiler.version":
                self.assertIn("%s=%s" % (setting, value), info)
            else:
                self.assertIn("compiler.version=14", info)
Beispiel #9
0
 def _check(self, install_path):
     settings_path = self.client.client_cache.settings_path
     self.assertEqual(load(settings_path).splitlines(), settings_yml.splitlines())
     registry_path = self.client.client_cache.registry
     registry = RemoteRegistry(registry_path, TestBufferConanOutput())
     self.assertEqual(registry.remotes,
                      [Remote("myrepo1", "https://myrepourl.net", False),
                       Remote("my-repo-2", "https://myrepo2.com", True),
                       ])
     self.assertEqual(registry.refs, {"MyPkg/0.1@user/channel": "my-repo-2"})
     self.assertEqual(sorted(os.listdir(self.client.client_cache.profiles_path)),
                      sorted(["default", "linux", "windows"]))
     self.assertEqual(load(os.path.join(self.client.client_cache.profiles_path, "linux")).splitlines(),
                      linux_profile.splitlines())
     self.assertEqual(load(os.path.join(self.client.client_cache.profiles_path, "windows")).splitlines(),
                      win_profile.splitlines())
     conan_conf = ConanClientConfigParser(self.client.client_cache.conan_conf_path)
     self.assertEqual(conan_conf.get_item("log.run_to_output"), "False")
     self.assertEqual(conan_conf.get_item("log.run_to_file"), "False")
     self.assertEqual(conan_conf.get_item("log.level"), "10")
     self.assertEqual(conan_conf.get_item("general.compression_level"), "6")
     self.assertEqual(conan_conf.get_item("general.sysrequires_sudo"), "True")
     self.assertEqual(conan_conf.get_item("general.cpu_count"), "1")
     self.assertEqual(conan_conf.get_item("general.config_install"), install_path)
     self.assertEqual(conan_conf.get_item("proxies.no_proxy"), "mylocalhost")
     self.assertEqual(conan_conf.get_item("proxies.https"), "None")
     self.assertEqual(conan_conf.get_item("proxies.http"), "http://*****:*****@10.10.1.10:3128/")
     self.assertEqual("#Custom pylint",
                      load(os.path.join(self.client.client_cache.conan_folder, "pylintrc")))
     self.assertEqual("",
                      load(os.path.join(self.client.client_cache.conan_folder, "python",
                                        "__init__.py")))
Beispiel #10
0
    def conan_env_deps_test(self):
        client = TestClient()
        conanfile = '''
from conans import ConanFile

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"
    def package_info(self):
        self.env_info.var1="bad value"
        self.env_info.var2.append("value2")
        self.env_info.var3="Another value"
        self.env_info.path = "/dir"
'''
        files = {"conanfile.py": conanfile}
        client.save(files)
        client.run("export . lasote/stable")
        conanfile = '''
from conans import ConanFile

class HelloConan(ConanFile):
    name = "Hello2"
    version = "0.1"
    def config(self):
        self.requires("Hello/0.1@lasote/stable")

    def package_info(self):
        self.env_info.var1="good value"
        self.env_info.var2.append("value3")
        self.env_info.CPPFLAGS.append("MYCPPFLAG=1")
    '''
        files["conanfile.py"] = conanfile
        client.save(files, clean_first=True)
        client.run("export . lasote/stable")
        client.run("install Hello2/0.1@lasote/stable --build "
                   "-g virtualenv -e CPPFLAGS=[OtherFlag=2]")
        ext = "bat" if platform.system() == "Windows" else "sh"
        self.assertTrue(os.path.exists(os.path.join(client.current_folder, "activate.%s" % ext)))
        self.assertTrue(os.path.exists(os.path.join(client.current_folder, "deactivate.%s" % ext)))
        activate_contents = load(os.path.join(client.current_folder, "activate.%s" % ext))
        deactivate_contents = load(os.path.join(client.current_folder, "deactivate.%s" % ext))
        self.assertNotIn("bad value", activate_contents)
        if platform.system() == "Windows":
            self.assertIn("var1=good value", activate_contents)
        else:
            self.assertIn('var1="good value"', activate_contents)

        if platform.system() == "Windows":
            self.assertIn('var2=value3;value2;%var2%', activate_contents)
        else:
            self.assertIn('var2="value3":"value2":$var2', activate_contents)
            self.assertIn('CPPFLAGS="OtherFlag=2 MYCPPFLAG=1 $CPPFLAGS"', activate_contents)
        self.assertIn("Another value", activate_contents)
        if platform.system() == "Windows":
            self.assertIn("PATH=/dir", activate_contents)
        else:
            self.assertIn("PATH=\"/dir\"", activate_contents)

        self.assertIn('var1=', deactivate_contents)
        self.assertIn('var2=', deactivate_contents)
Beispiel #11
0
    def basic_with_linked_dir_test(self):
        if platform.system() == "Linux" or platform.system() == "Darwin":
            folder1 = temp_folder()
            sub1 = os.path.join(folder1, "subdir1")
            sub2 = os.path.join(folder1, "subdir2")
            os.makedirs(sub1)
            os.symlink("subdir1", sub2)
            save(os.path.join(sub1, "file1.txt"), "Hello1")
            save(os.path.join(sub1, "file2.c"), "Hello2")
            save(os.path.join(sub1, "sub1/file1.txt"), "Hello1 sub")

            folder2 = temp_folder()
            copier = FileCopier(folder1, folder2)
            copier("*.txt", "texts")
            self.assertEqual("Hello1", load(os.path.join(folder2, "texts/subdir1/file1.txt")))
            self.assertEqual("Hello1 sub", load(os.path.join(folder2, "texts/subdir1/sub1/file1.txt")))
            self.assertEqual("Hello1", load(os.path.join(folder2, "texts/subdir2/file1.txt")))
            self.assertEqual(['file1.txt', 'sub1'].sort(), os.listdir(os.path.join(folder2, "texts/subdir2")).sort())

            folder2 = temp_folder()
            copier = FileCopier(folder1, folder2)
            copier("*.txt", "texts", "subdir1")
            self.assertEqual("Hello1", load(os.path.join(folder2, "texts/file1.txt")))
            self.assertEqual("Hello1 sub", load(os.path.join(folder2, "texts/sub1/file1.txt")))
            self.assertNotIn("subdir2", os.listdir(os.path.join(folder2, "texts")))
Beispiel #12
0
    def _check_conaninfo(self, client):
        # Check that conaninfo is correct
        ref_debug = PackageReference.loads("Pkg/0.1@user/channel:"
                                           "f3989dcba0ab50dc5ed9b40ede202bdd7b421f09")
        conaninfo = load(os.path.join(client.client_cache.package(ref_debug), "conaninfo.txt"))
        self.assertIn("os=Windows", conaninfo)
        self.assertIn("build_type=Debug", conaninfo)
        self.assertNotIn("Release", conaninfo)

        ref_release = PackageReference.loads("Pkg/0.1@user/channel:"
                                             "ab2e9f86b4109980930cdc685f4a320b359e7bb4")
        conaninfo = load(os.path.join(client.client_cache.package(ref_release), "conaninfo.txt"))
        self.assertIn("os=Windows", conaninfo)
        self.assertIn("build_type=Release", conaninfo)
        self.assertNotIn("Debug", conaninfo)

        ref_debug = PackageReference.loads("Pkg/0.1@user/channel:"
                                           "322de4b4a41f905f6b18f454ab5f498690b39c2a")
        conaninfo = load(os.path.join(client.client_cache.package(ref_debug), "conaninfo.txt"))
        self.assertIn("os=Linux", conaninfo)
        self.assertIn("build_type=Debug", conaninfo)
        self.assertNotIn("Release", conaninfo)

        ref_release = PackageReference.loads("Pkg/0.1@user/channel:"
                                             "24c3aa2d6c5929d53bd86b31e020c55d96b265c7")
        conaninfo = load(os.path.join(client.client_cache.package(ref_release), "conaninfo.txt"))
        self.assertIn("os=Linux", conaninfo)
        self.assertIn("build_type=Release", conaninfo)
        self.assertNotIn("Debug", conaninfo)
Beispiel #13
0
    def basic_test(self):
        client = TestClient()
        zlib = '''
from conans import ConanFile

class ConanLib(ConanFile):
    name = "zlib"
    version = "0.1"
    options = {"shared": [True, False]}
    default_options= "shared=False"
'''

        client.save({"conanfile.py": zlib})
        client.run("export lasote/testing")

        project = """[requires]
zlib/0.1@lasote/testing
"""
        client.save({"conanfile.txt": project}, clean_first=True)

        client.run("install -o zlib:shared=True --build=missing")
        self.assertIn("zlib/0.1@lasote/testing:2a623e3082a38f90cd2c3d12081161412de331b0",
                      client.user_io.out)
        conaninfo = load(os.path.join(client.current_folder, CONANINFO))
        self.assertIn("zlib:shared=True", conaninfo)

        # Options not cached anymore
        client.run("install --build=missing")
        self.assertIn("zlib/0.1@lasote/testing:5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9",
                      client.user_io.out)
        conaninfo = load(os.path.join(client.current_folder, CONANINFO))
        self.assertNotIn("zlib:shared=True", conaninfo)
Beispiel #14
0
    def download_with_sources_test(self):
        server = TestServer()
        servers = {"default": server,
                   "other": TestServer()}

        client = TestClient(servers=servers, users={"default": [("lasote", "mypass")],
                                                    "other": [("lasote", "mypass")]})
        conanfile = """from conans import ConanFile
class Pkg(ConanFile):
    name = "pkg"
    version = "0.1"
    exports_sources = "*"
"""
        client.save({"conanfile.py": conanfile,
                     "file.h": "myfile.h",
                     "otherfile.cpp": "C++code"})
        client.run("export . lasote/stable")

        ref = ConanFileReference.loads("pkg/0.1@lasote/stable")
        self.assertTrue(os.path.exists(client.paths.conanfile(ref)))

        client.run("upload pkg/0.1@lasote/stable")
        client.run("remove pkg/0.1@lasote/stable -f")
        self.assertFalse(os.path.exists(client.paths.export(ref)))

        client.run("download pkg/0.1@lasote/stable")
        self.assertIn("Downloading conan_sources.tgz", client.out)
        source = client.client_cache.export_sources(ref)
        self.assertEqual("myfile.h", load(os.path.join(source, "file.h")))
        self.assertEqual("C++code", load(os.path.join(source, "otherfile.cpp")))
Beispiel #15
0
    def global_test(self):
        client = TestClient()
        files = {'conanfile.py': base_conanfile.replace("%GLOBAL%",
                                                        "self.global_system_requirements=True")}
        client.save(files)
        client.run("export user/testing")
        client.run("install Test/0.1@user/testing --build missing")
        self.assertIn("*+Running system requirements+*", client.user_io.out)
        conan_ref = ConanFileReference.loads("Test/0.1@user/testing")
        package_ref = PackageReference(conan_ref, "a527106fd9f2e3738a55b02087c20c0a63afce9d")
        self.assertFalse(os.path.exists(client.paths.system_reqs_package(package_ref)))
        load_file = load(client.paths.system_reqs(conan_ref))
        self.assertIn("Installed my stuff", load_file)

        # Run again
        client.run("install Test/0.1@user/testing --build missing")
        self.assertNotIn("*+Running system requirements+*", client.user_io.out)
        self.assertFalse(os.path.exists(client.paths.system_reqs_package(package_ref)))
        load_file = load(client.paths.system_reqs(conan_ref))
        self.assertIn("Installed my stuff", load_file)

        # Run with different option
        client.run("install Test/0.1@user/testing -o myopt=False --build missing")
        self.assertNotIn("*+Running system requirements+*", client.user_io.out)
        package_ref2 = PackageReference(conan_ref, "54c9626b48cefa3b819e64316b49d3b1e1a78c26")
        self.assertFalse(os.path.exists(client.paths.system_reqs_package(package_ref)))
        self.assertFalse(os.path.exists(client.paths.system_reqs_package(package_ref2)))
        load_file = load(client.paths.system_reqs(conan_ref))
        self.assertIn("Installed my stuff", load_file)

        # remove packages
        client.run("remove Test* -f -p")
        self.assertFalse(os.path.exists(client.paths.system_reqs_package(package_ref)))
        self.assertFalse(os.path.exists(client.paths.system_reqs_package(package_ref2)))
        self.assertFalse(os.path.exists(client.paths.system_reqs(conan_ref)))
Beispiel #16
0
    def fail_test_package_test(self):
        client = TestClient()
        conanfile = """
from conans import ConanFile

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"
    exports = "*"

    def package(self):
        self.copy("*")
"""
        test_conanfile = """
from conans import ConanFile, CMake
import os

class HelloReuseConan(ConanFile):
    requires = "Hello/0.1@lasote/stable"

    def test(self):
        self.conanfile_directory
"""
        client.save({"conanfile.py": conanfile,
                     "FindXXX.cmake": "Hello FindCmake",
                     "test/conanfile.py": test_conanfile})
        client.run("test_package")
        ref = PackageReference.loads("Hello/0.1@lasote/stable:"
                                     "5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
        self.assertEqual("Hello FindCmake",
                         load(os.path.join(client.paths.package(ref), "FindXXX.cmake")))
        client.save({"FindXXX.cmake": "Bye FindCmake"})
        client.run("test_package")
        self.assertEqual("Bye FindCmake",
                         load(os.path.join(client.paths.package(ref), "FindXXX.cmake")))
Beispiel #17
0
    def _test_check(self, test_folder, test_folder_name):
        """ To ensure that the 0.9 version new layout is detected and users warned
        """
        # Check old tests, format
        test_conanfile = os.path.join(test_folder, "conanfile.py")
        if not os.path.exists(test_conanfile):
            raise ConanException("Test conanfile.py does not exist")
        test_conanfile_content = load(test_conanfile)
        if ".conanfile_directory" not in test_conanfile_content:
            self._user_io.out.error("""******* conan test command layout has changed *******

In your "%s" folder 'conanfile.py' you should use the
path to the conanfile_directory, something like:

    self.run('cmake %%s %%s' %% (self.conanfile_directory, cmake.command_line))

 """ % (test_folder_name))

        # Test the CMakeLists, if existing
        test_cmake = os.path.join(test_folder, "CMakeLists.txt")
        if os.path.exists(test_cmake):
            test_cmake_content = load(test_cmake)
            if "${CMAKE_BINARY_DIR}/conanbuildinfo.cmake" not in test_cmake_content:
                self._user_io.out.error("""******* conan test command layout has changed *******

In your "%s" folder 'CMakeLists.txt' you should use the
path to the CMake binary directory, like this:

   include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)

 """ % (test_folder_name))
Beispiel #18
0
    def basic_test(self):
        folder1 = temp_folder()
        sub1 = os.path.join(folder1, "subdir1")
        sub2 = os.path.join(folder1, "subdir2")
        save(os.path.join(sub1, "file1.txt"), "Hello1")
        save(os.path.join(sub1, "file2.c"), "Hello2")
        save(os.path.join(sub1, "sub1/file1.txt"), "Hello1 sub")
        save(os.path.join(sub1, "sub1/file2.c"), "Hello2 sub")
        save(os.path.join(sub2, "file1.txt"), "2 Hello1")
        save(os.path.join(sub2, "file2.c"), "2 Hello2")

        folder2 = temp_folder()
        copier = FileCopier(folder1, folder2)
        copier("*.txt", "texts")
        self.assertEqual("Hello1", load(os.path.join(folder2, "texts/subdir1/file1.txt")))
        self.assertEqual("Hello1 sub", load(os.path.join(folder2, "texts/subdir1/sub1/file1.txt")))
        self.assertEqual("2 Hello1", load(os.path.join(folder2, "texts/subdir2/file1.txt")))
        self.assertEqual(['file1.txt'], os.listdir(os.path.join(folder2, "texts/subdir2")))

        folder2 = temp_folder()
        copier = FileCopier(folder1, folder2)
        copier("*.txt", "texts", "subdir1")
        self.assertEqual("Hello1", load(os.path.join(folder2, "texts/file1.txt")))
        self.assertEqual("Hello1 sub", load(os.path.join(folder2, "texts/sub1/file1.txt")))
        self.assertNotIn("subdir2", os.listdir(os.path.join(folder2, "texts")))
Beispiel #19
0
    def custom_settings_test(self):
        settings = """os:
    None:
    Windows:
        subsystem: [None, cygwin]
    Linux:
compiler: [gcc, visual]
"""
        client = TestClient()
        save(client.paths.settings_path, settings)
        save(client.paths.default_profile_path, "")
        conanfile = """from conans import ConanFile
class Pkg(ConanFile):
    settings = "os", "compiler"
"""
        client.save({"conanfile.py": conanfile})
        client.run("create . Pkg/0.1@lasote/testing -s compiler=gcc")
        self.assertIn("544c1d8c53e9d269737e68e00ec66716171d2704", client.out)
        client.run("search Pkg/0.1@lasote/testing")
        self.assertNotIn("os: None", client.out)
        package_reference = PackageReference.loads("Pkg/0.1@lasote/testing:544c1d8c53e9d269737e68e00ec66716171d2704")
        info_path = os.path.join(client.paths.package(package_reference), CONANINFO)
        info = load(info_path)
        self.assertNotIn("os", info)
        # Explicitly specifying None, put it in the conaninfo.txt, but does not affect the hash
        client.run("create . Pkg/0.1@lasote/testing -s compiler=gcc -s os=None")
        self.assertIn("544c1d8c53e9d269737e68e00ec66716171d2704", client.out)
        client.run("search Pkg/0.1@lasote/testing")
        self.assertIn("os: None", client.out)
        info = load(info_path)
        self.assertIn("os", info)
Beispiel #20
0
    def new_ci_test(self):
        client = TestClient()
        client.run('new MyPackage/1.3@myuser/testing -cis -ciw -cilg -cilc -cio -ciu=myurl')
        root = client.current_folder
        build_py = load(os.path.join(root, "build.py"))
        self.assertIn('builder.add_common_builds(shared_option_name="MyPackage:shared")',
                      build_py)
        self.assertNotIn('visual_versions=', build_py)
        self.assertNotIn('gcc_versions=', build_py)
        self.assertNotIn('clang_versions=', build_py)
        self.assertNotIn('apple_clang_versions=', build_py)
        appveyor = load(os.path.join(root, "appveyor.yml"))
        self.assertIn("CONAN_UPLOAD: \"myurl\"", appveyor)
        self.assertIn('CONAN_REFERENCE: "MyPackage/1.3"', appveyor)
        self.assertIn('CONAN_USERNAME: "******"', appveyor)
        self.assertIn('CONAN_CHANNEL: "testing"', appveyor)
        self.assertIn('CONAN_VISUAL_VERSIONS: 12', appveyor)
        self.assertIn('CONAN_VISUAL_VERSIONS: 14', appveyor)
        self.assertIn('CONAN_VISUAL_VERSIONS: 15', appveyor)

        travis = load(os.path.join(root, ".travis.yml"))
        self.assertIn("- CONAN_UPLOAD: \"myurl\"", travis)
        self.assertIn('- CONAN_REFERENCE: "MyPackage/1.3"', travis)
        self.assertIn('- CONAN_USERNAME: "******"', travis)
        self.assertIn('- CONAN_CHANNEL: "testing"', travis)
        self.assertIn('env: CONAN_GCC_VERSIONS=5.4 CONAN_DOCKER_IMAGE=lasote/conangcc54',
                      travis)
Beispiel #21
0
    def test_filename(self):
        client = TestClient()
        conanfile = """
from conans import ConanFile
class TestConan(ConanFile):
    name = "Hello"
    version = "1.2"
"""
        client.save({"myconanfile.py": conanfile,
                     "conanfile.py": ""})

        if platform.system() == "Windows":
            error = client.run("export lasote/stable -f MyConanfile.py", ignore_error=True)
            self.assertTrue(error)
            self.assertIn("Wrong 'MyConanfile.py' case", client.user_io.out)

        client.run("export lasote/stable --file=myconanfile.py")
        self.assertIn("Hello/1.2@lasote/stable: A new conanfile.py version was exported",
                      client.user_io.out)
        conan_ref = ConanFileReference("Hello", "1.2", "lasote", "stable")
        export_path = client.paths.export(conan_ref)
        conanfile = load(os.path.join(export_path, "conanfile.py"))
        self.assertIn('name = "Hello"', conanfile)
        manifest = load(os.path.join(export_path, "conanmanifest.txt"))
        self.assertIn('conanfile.py: cac514c81a0af0d87fa379b0bf16fbaa', manifest)
Beispiel #22
0
 def _assert_pkg(self, folder):
     self.assertEqual(sorted(['file.h', 'myartifact.lib', 'subdir', 'conaninfo.txt',
                              'conanmanifest.txt']),
                      sorted(os.listdir(folder)))
     self.assertEqual(load(os.path.join(folder, "myartifact.lib")),
                      "artifact contents!")
     self.assertEqual(load(os.path.join(folder, "subdir/myartifact2.lib")),
                      "artifact2 contents!")
Beispiel #23
0
    def test_base(self):

        base = '''
from conans import ConanFile

class HelloConan2(ConanFile):
    name = "test"
    version = "1.9"
    requires = "lib/0.1@user/channel"
    options = {"test_option": [1, 2, 3]}
    default_options="test_option=2"
    my_flag = False

    def build(self):
        self.output.info("MyFlag %s" % self.my_flag)
    '''
        extension = '''
from conans import ConanFile, CMake
from conanfile import HelloConan2

class DevConanFile(HelloConan2):
    my_flag = True

    def config(self):
        self.options["otherlib"].otherlib_option = 1

    def requirements(self):
        self.requires("otherlib/0.2@user/channel")

    '''
        files = {"conanfile.py": base,
                 "conanfile_dev.py": extension}

        client = TestClient(self.base_folder)
        client.save(files)
        client.run("install . --build")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("lib/0.1@user/channel", conaninfo)
        self.assertIn("test_option=2", conaninfo)
        self.assertNotIn("otherlib/0.2@user/channel", conaninfo)
        self.assertNotIn("otherlib:otherlib_option=1", conaninfo)
        client.run("build .")
        self.assertIn("MyFlag False", client.user_io.out)
        client.run("info .")
        self.assertIn("lib/0.1@user/channel", client.user_io.out)
        self.assertNotIn("otherlib/0.2@user/channel", client.user_io.out)

        client.run("install conanfile_dev.py --build")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("lib/0.1@user/channel", conaninfo)
        self.assertIn("test_option=2", conaninfo)
        self.assertIn("otherlib/0.2@user/channel", conaninfo)
        self.assertIn("otherlib:otherlib_option=1", conaninfo)
        client.run("build ./conanfile_dev.py")
        self.assertIn("MyFlag True", client.user_io.out)
        client.run("info conanfile_dev.py")
        self.assertIn("lib/0.1@user/channel", client.user_io.out)
        self.assertIn("otherlib/0.2@user/channel", client.user_io.out)
    def test_something(self):
        tmp = temp_folder()
        old_conf = """
[general]
the old general

[settings_defaults]
some settings

[other_section]

with other values

"""
        conf_path = os.path.join(tmp, "conan.conf")
        default_profile_path = os.path.join(tmp, "conan_default")
        save(conf_path, old_conf)

        migrate_to_default_profile(conf_path, default_profile_path)

        new_content = load(conf_path)
        self.assertEquals(new_content, """
[general]
the old general

[other_section]

with other values

""")

        default_profile = load(default_profile_path)
        self.assertEquals(default_profile, """[settings]
some settings""")

        old_conf = """
[general]
the old general

[settings_defaults]
some settings

"""
        conf_path = os.path.join(tmp, "conan.conf")
        default_profile_path = os.path.join(tmp, "conan_default")
        save(conf_path, old_conf)

        migrate_to_default_profile(conf_path, default_profile_path)
        default_profile = load(default_profile_path)
        self.assertEquals(default_profile, """[settings]
some settings""")

        new_content = load(conf_path)
        self.assertEquals(new_content, """
[general]
the old general

""")
Beispiel #25
0
    def build(self, conanfile_path, current_path, test=False, filename=None, profile_name=None):
        """ Call to build() method saved on the conanfile.py
        param conanfile_path: the original source directory of the user containing a
                            conanfile.py
        """
        logger.debug("Building in %s" % current_path)
        logger.debug("Conanfile in %s" % conanfile_path)

        if filename and filename.endswith(".txt"):
            raise ConanException("A conanfile.py is needed to call 'conan build'")

        conanfile_file = os.path.join(conanfile_path, filename or CONANFILE)

        try:
            output = ScopedOutput("Project", self._user_io.out)
            conan_file = self._loader(current_path).load_conan(conanfile_file, output,
                                                               consumer=True)
        except NotFoundException:
            # TODO: Auto generate conanfile from requirements file
            raise ConanException("'%s' file is needed for build.\n"
                                 "Create a '%s' and move manually the "
                                 "requirements and generators from '%s' file"
                                 % (CONANFILE, CONANFILE, CONANFILE_TXT))
        try:
            build_info_file = os.path.join(current_path, BUILD_INFO)
            if os.path.exists(build_info_file):
                try:
                    deps_cpp_info = DepsCppInfo.loads(load(build_info_file))
                    conan_file.deps_cpp_info = deps_cpp_info
                except:
                    pass

            env_file = os.path.join(current_path, "conanenv.txt")
            if os.path.exists(env_file):
                try:
                    deps_env_info = DepsEnvInfo.loads(load(env_file))
                    conan_file.deps_env_info = deps_env_info
                except:
                    pass

            os.chdir(current_path)
            conan_file._conanfile_directory = conanfile_path
            # Append env_vars to execution environment and clear when block code ends
            profile = self._read_profile(profile_name)
            env_vars = self._read_profile_env_vars(profile)
            with environment_append(env_vars):
                conan_file.build()

            if test:
                conan_file.test()
        except ConanException:
            raise  # Raise but not let to reach the Exception except (not print traceback)
        except Exception:
            import traceback
            trace = traceback.format_exc().split('\n')
            raise ConanException("Unable to build it successfully\n%s" % '\n'.join(trace[3:]))
Beispiel #26
0
    def test_simple_fields(self):
        # Result of a create
        files = cpp_hello_conan_files("CC", "1.0", build=False)
        self.client.save(files, clean_first=True)
        self.client.run("create . private_user/channel --json=myfile.json ")
        my_json = json.loads(load(os.path.join(self.client.current_folder, "myfile.json")))
        self.assertFalse(my_json["error"])
        self.assertEquals(my_json["installed"][0]["recipe"]["id"], "CC/1.0@private_user/channel")
        self.assertFalse(my_json["installed"][0]["recipe"]["dependency"])
        self.assertTrue(my_json["installed"][0]["recipe"]["cache"])
        self.assertIsNone(my_json["installed"][0]["recipe"]["remote"])
        self.assertTrue(my_json["installed"][0]["packages"][0]["built"])

        # Result of an install retrieving only the recipe
        self.client.run("upload CC/1.0@private_user/channel -c")
        self.client.run("remove '*' -f")
        self.client.run("install CC/1.0@private_user/channel --json=myfile.json --build missing ")
        my_json = json.loads(load(os.path.join(self.client.current_folder, "myfile.json")))

        the_time_str = my_json["installed"][0]["recipe"]["time"]
        self.assertIn("T", the_time_str) # Weak validation of the ISO 8601
        self.assertFalse(my_json["error"])
        self.assertEquals(my_json["installed"][0]["recipe"]["id"], "CC/1.0@private_user/channel")
        self.assertTrue(my_json["installed"][0]["recipe"]["dependency"])
        self.assertFalse(my_json["installed"][0]["recipe"]["cache"])
        self.assertTrue(my_json["installed"][0]["recipe"]["downloaded"])
        self.assertIsNotNone(my_json["installed"][0]["recipe"]["remote"])
        self.assertTrue(my_json["installed"][0]["packages"][0]["built"])

        # Upload the binary too
        self.client.run("upload CC/1.0@private_user/channel --all -c")
        self.client.run("remove '*' -f")
        self.client.run("install CC/1.0@private_user/channel --json=myfile.json")
        my_json = json.loads(load(os.path.join(self.client.current_folder, "myfile.json")))

        self.assertFalse(my_json["error"])
        self.assertEquals(my_json["installed"][0]["recipe"]["id"], "CC/1.0@private_user/channel")
        self.assertFalse(my_json["installed"][0]["recipe"]["cache"])
        self.assertTrue(my_json["installed"][0]["recipe"]["downloaded"])
        self.assertIsNotNone(my_json["installed"][0]["recipe"]["remote"])
        self.assertFalse(my_json["installed"][0]["packages"][0]["built"])
        self.assertTrue(my_json["installed"][0]["packages"][0]["downloaded"])

        # Force build
        self.client.run("remove '*' -f")
        self.client.run("install CC/1.0@private_user/channel --json=myfile.json --build")
        my_json = json.loads(load(os.path.join(self.client.current_folder, "myfile.json")))

        self.assertFalse(my_json["error"])
        self.assertEquals(my_json["installed"][0]["recipe"]["id"], "CC/1.0@private_user/channel")
        self.assertFalse(my_json["installed"][0]["recipe"]["cache"])
        self.assertTrue(my_json["installed"][0]["recipe"]["downloaded"])
        self.assertIsNotNone(my_json["installed"][0]["recipe"]["remote"])
        self.assertTrue(my_json["installed"][0]["packages"][0]["built"])
        self.assertFalse(my_json["installed"][0]["packages"][0]["downloaded"])
Beispiel #27
0
    def invalid_settings_test4(self):
        content = """
from conans import ConanFile

class SayConan(ConanFile):
    name = "Say"
    version = "0.1"
    settings = "os"
"""

        self.client.save({CONANFILE: content})
        self.client.run("install . -s os=ChromeOS --build missing", ignore_error=True)
        self.assertIn(bad_value_msg("settings.os", "ChromeOS",
                                    ['Android', 'Arduino', 'FreeBSD', 'Linux', 'Macos', 'SunOS', 'Windows',
                                     'WindowsStore', 'iOS', 'tvOS', 'watchOS']),
                      str(self.client.user_io.out))

        # Now add new settings to config and try again
        config = load(self.client.paths.settings_path)
        config = config.replace("Windows:%s" % os.linesep,
                                "Windows:%s    ChromeOS:%s" % (os.linesep, os.linesep))

        save(self.client.paths.settings_path, config)
        self.client.run("install . -s os=ChromeOS --build missing")
        self.assertIn('Generated conaninfo.txt', str(self.client.user_io.out))

        # Settings is None
        content = """
from conans import ConanFile

class SayConan(ConanFile):
    name = "Say"
    version = "0.1"
    settings = None
"""
        self.client.save({CONANFILE: content})
        self.client.run("install . --build missing")
        self.assertIn('Generated conaninfo.txt', str(self.client.user_io.out))
        conan_info = ConanInfo.loads(load(os.path.join(self.client.current_folder, CONANINFO)))
        self.assertEquals(conan_info.settings.dumps(), "")

        # Settings is {}
        content = """
from conans import ConanFile

class SayConan(ConanFile):
    name = "Say"
    version = "0.1"
    settings = {}
"""
        self.client.save({CONANFILE: content})
        self.client.run("install . --build missing")
        self.assertIn('Generated conaninfo.txt', str(self.client.user_io.out))
        conan_info = ConanInfo.loads(load(os.path.join(self.client.current_folder, CONANINFO)))
        self.assertEquals(conan_info.settings.dumps(), "")
Beispiel #28
0
    def test_errors(self):

        # Missing recipe
        error = self.client.run("install CC/1.0@private_user/channel --json=myfile.json",
                                ignore_error=True)
        self.assertTrue(error)
        my_json = json.loads(load(os.path.join(self.client.current_folder, "myfile.json")))
        self.assertTrue(my_json["error"])
        self.assertEquals(len(my_json["installed"]), 1)
        self.assertFalse(my_json["installed"][0]["recipe"]["cache"])
        self.assertFalse(my_json["installed"][0]["recipe"]["downloaded"])
        self.assertEquals(my_json["installed"][0]["recipe"]["error"],
                          {'type': 'missing', 'remote': None,
                          'description': "Unable to find 'CC/1.0@private_user/channel' in remotes"})

        # Missing binary package
        files = cpp_hello_conan_files("CC", "1.0", build=False)
        self.client.save(files, clean_first=True)
        self.client.run("create . private_user/channel --json=myfile.json ")
        self.client.run("upload CC/1.0@private_user/channel -c")
        self.client.run("remove '*' -f")
        error = self.client.run("install CC/1.0@private_user/channel --json=myfile.json",
                                ignore_error=True)
        my_json = json.loads(load(os.path.join(self.client.current_folder, "myfile.json")))

        self.assertTrue(error)
        self.assertTrue(my_json["error"])
        self.assertEquals(len(my_json["installed"]), 1)
        self.assertFalse(my_json["installed"][0]["recipe"]["cache"])
        self.assertTrue(my_json["installed"][0]["recipe"]["downloaded"])
        self.assertFalse(my_json["installed"][0]["recipe"]["error"])
        self.assertEquals(len(my_json["installed"][0]["packages"]), 1)
        self.assertFalse(my_json["installed"][0]["packages"][0]["cache"])
        self.assertFalse(my_json["installed"][0]["packages"][0]["downloaded"])
        self.assertEquals(my_json["installed"][0]["packages"][0]["error"]["type"], "missing")
        self.assertIsNone(my_json["installed"][0]["packages"][0]["error"]["remote"])
        self.assertIn("Can't find a 'CC/1.0@private_user/channel' package",
                      my_json["installed"][0]["packages"][0]["error"]["description"])

        # Error building
        files["conanfile.py"] = files["conanfile.py"].replace("def build2(self):",
                                                              """
    def build(self):
        raise Exception("Build error!")
        """)

        self.client.save(files, clean_first=True)
        self.client.run("create . private_user/channel --json=myfile.json ", ignore_error=True)
        my_json = json.loads(load(os.path.join(self.client.current_folder, "myfile.json")))
        self.assertTrue(my_json["error"])
        self.assertEquals(my_json["installed"][0]["packages"][0]["error"]["type"], "building")
        self.assertIsNone(my_json["installed"][0]["packages"][0]["error"]["remote"])
        self.assertIn("CC/1.0@private_user/channel: Error in build() method, line 36",
                      my_json["installed"][0]["packages"][0]["error"]["description"])
Beispiel #29
0
    def test_run_log_file_package_test(self):
        '''Check if the log file is generated and packaged'''

        base = '''
from conans import ConanFile

class HelloConan(ConanFile):
    name = "Hello0"
    version = "0.1"

    def build(self):
        self.run('echo "Simulating cmake..."')

    def package(self):
        self.copy(pattern="%s", dst="", keep_path=False)
    ''' % RUN_LOG_NAME

        def _install_a_package(print_commands_to_output, generate_run_log_file):

            runner = ConanRunner(print_commands_to_output, generate_run_log_file,
                                 log_run_to_output=True)

            client = TestClient(servers=self.servers,
                                users={"default": [("lasote", "mypass")]},
                                runner=runner)
            conan_reference = ConanFileReference.loads("Hello0/0.1@lasote/stable")
            files = {}
            files[CONANFILE] = base
            client.save(files)
            client.run("user lasote -p mypass -r default")
            client.run("export . lasote/stable")
            client.run("install %s --build missing" % str(conan_reference))
            package_dir = client.client_cache.packages(ConanFileReference.loads("Hello0/0.1@lasote/stable"))
            package_dir = os.path.join(package_dir, os.listdir(package_dir)[0])
            log_file_packaged = os.path.join(package_dir, RUN_LOG_NAME)
            return log_file_packaged, client.user_io.out

        log_file_packaged, output = _install_a_package(False, True)
        self.assertIn("Copied 1 '.log' file: conan_run.log", output)
        self.assertTrue(os.path.exists(log_file_packaged))
        contents = load(log_file_packaged)
        self.assertIn("Simulating cmake...", contents)
        self.assertNotIn("----Running------%s> echo" % os.linesep, contents)

        log_file_packaged, output = _install_a_package(True, True)
        self.assertIn("Copied 1 '.log' file: conan_run.log", output)
        self.assertTrue(os.path.exists(log_file_packaged))
        contents = load(log_file_packaged)
        self.assertIn("Simulating cmake...", contents)
        self.assertIn("----Running------%s> echo" % os.linesep, contents)

        log_file_packaged, output = _install_a_package(False, False)
        self.assertNotIn("Copied 1 '.log' file: conan_run.log", output)
        self.assertFalse(os.path.exists(log_file_packaged))
Beispiel #30
0
    def basic_test(self):
        client = TestClient()
        base = '''
from conans import ConanFile
from conans.util.files import load, save
import os

class ConanLib(ConanFile):
    name = "lib"
    version = "0.1"
    short_paths = True

    def source(self):
        extra_path = "1/" * 108
        os.makedirs(extra_path)
        myfile = os.path.join(extra_path, "myfile.txt")
        # print("File length ", len(myfile))
        save(myfile, "Hello extra path length")

    def build(self):
        extra_path = "1/" * 108
        myfile = os.path.join(extra_path, "myfile2.txt")
        # print("File length ", len(myfile))
        save(myfile, "Hello2 extra path length")

    def package(self):
        self.copy("*.txt", keep_path=False)
'''

        files = {"conanfile.py": base}
        client.save(files)
        client.run("export user/channel")
        client.run("install lib/0.1@user/channel --build")
        package_ref = PackageReference.loads("lib/0.1@user/channel:"
                                             "5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
        package_folder = client.client_cache.package(package_ref)
        file1 = load(os.path.join(package_folder, "myfile.txt"))
        self.assertEqual("Hello extra path length", file1)
        file2 = load(os.path.join(package_folder, "myfile2.txt"))
        self.assertEqual("Hello2 extra path length", file2)

        if platform.system() == "Windows":
            conan_ref = ConanFileReference.loads("lib/0.1@user/channel")
            source_folder = client.client_cache.source(conan_ref)
            link_source = load(os.path.join(source_folder, ".conan_link"))
            self.assertTrue(os.path.exists(link_source))

            build_folder = client.client_cache.build(package_ref)
            link_build = load(os.path.join(build_folder, ".conan_link"))
            self.assertTrue(os.path.exists(link_build))

            client.run("remove lib* -f")
            self.assertFalse(os.path.exists(link_source))
            self.assertFalse(os.path.exists(link_build))
Beispiel #31
0
    def test_update_settings(self):
        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]
arch: [x86, x86_64, armv6, armv7, armv7hf, armv8]
compiler:
    gcc:
        version: ["4.4", "4.5", "4.6", "4.7", "4.8", "4.9", "5.1", "5.2", "5.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"]
        libcxx: [libstdc++, libc++]

"""
        files = {"conanfile.py": file_content}
        client = TestClient()
        save(client.paths.settings_path, prev_settings)
        conf = load(client.paths.conan_conf_path)
        conf = conf.replace("build_type=Release", "")
        self.assertNotIn("build_type", conf)
        save(client.paths.conan_conf_path, conf)
        self.assertNotIn("build_type",
                         client.paths.conan_config.settings_defaults.dumps())
        client.save(files)
        client.run("export lasote/testing")
        self.assertNotIn("build_type", load(client.paths.settings_path))
        self.assertNotIn("build_type", load(client.paths.conan_conf_path))
        self.assertNotIn("build_type",
                         client.paths.conan_config.settings_defaults.dumps())

        client.run(
            "install test/1.9@lasote/testing --build -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")
        self.assertIn("build_type", load(client.paths.settings_path))

        client.run(
            "install test/1.9@lasote/testing --build -s compiler=gcc "
            "-s compiler.version=4.9 -s os=Windows -s build_type=None -s compiler.libcxx=libstdc++"
        )
        self.assertIn("390146894f59dda18c902ee25e649ef590140732",
                      client.user_io.out)
Beispiel #32
0
    def insource_build_test(self):
        client = TestClient()

        def files(name, depend=None):
            includes = ('#include "hello%s.h"' % depend) if depend else ""
            calls = ('hello%s();' % depend) if depend else ""
            deps = ('"Hello%s/0.1@lasote/stable"' % depend) if depend else "None"
            return {"conanfile.py": conanfile_build.format(deps=deps, name=name),
                    "src/hello%s.h" % name: hello_h.format(name=name),
                    "src/hello.cpp": hello_cpp.format(name=name, includes=includes, calls=calls),
                    "src/CMakeLists.txt": cmake.format(name=name)}

        C = os.path.join(client.current_folder, "C")
        B = os.path.join(client.current_folder, "B")
        A = os.path.join(client.current_folder, "A")
        client.save(files("C"), path=C)
        client.save(files("B", "C"), path=B)
        a = files("A", "B")
        a["src/CMakeLists.txt"] += "add_executable(app main.cpp)\ntarget_link_libraries(app helloA)\n"
        a["src/main.cpp"] = main_cpp
        client.save(a, path=A)

        project = """HelloB:
    folder: B
    includedirs: src
    cmakedir: src
    build: "'build' if '{os}'=='Windows' else 'build_{build_type}'.lower()"
    libdirs: "'build/{build_type}' if '{os}'=='Windows' else 'build_{build_type}'.lower()"
HelloC:
    folder: C
    includedirs: src
    cmakedir: src
    build: "'build' if '{os}'=='Windows' else 'build_{build_type}'.lower()"
    libdirs: "'build/{build_type}' if '{os}'=='Windows' else 'build_{build_type}'.lower()"
HelloA:
    folder: A
    cmakedir: src
    build: "'build' if '{os}'=='Windows' else 'build_{build_type}'.lower()"

root: HelloA
"""
        client.save({WORKSPACE_FILE: project})

        release = "build" if platform.system() == "Windows" else "build_release"
        debug = "build" if platform.system() == "Windows" else "build_debug"

        base_folder = client.current_folder
        client.run("install .")

        # Make sure nothing in local cache
        client.run("search")
        self.assertIn("There are no packages", client.out)

        # Check A
        content = load(os.path.join(client.current_folder, "A/%s/conanbuildinfo.cmake" % release))
        include_dirs_hellob = re.search('set\(CONAN_INCLUDE_DIRS_HELLOB "(.*)"\)', content).group(1)
        self.assertIn("void helloB();", load(os.path.join(include_dirs_hellob, "helloB.h")))
        include_dirs_helloc = re.search('set\(CONAN_INCLUDE_DIRS_HELLOC "(.*)"\)', content).group(1)
        self.assertIn("void helloC();", load(os.path.join(include_dirs_helloc, "helloC.h")))

        # Check B
        content = load(os.path.join(base_folder, "B/%s/conanbuildinfo.cmake" % release))
        include_dirs_helloc2 = re.search('set\(CONAN_INCLUDE_DIRS_HELLOC "(.*)"\)', content).group(1)
        self.assertEqual(include_dirs_helloc2, include_dirs_helloc)

        client.run("build C -bf=C/%s" % release)
        client.run("build B -bf=B/%s" % release)
        client.run("build A -bf=A/%s" % release)
        if platform.system() == "Windows":
            cmd_release = r".\A\build\Release\app"
            cmd_debug = r".\A\build\Debug\app"
        else:
            cmd_release = "./A/build_release/app"
            cmd_debug = "./A/build_debug/app"
        client.runner(cmd_release, cwd=client.current_folder)
        self.assertIn("Hello World C Release!", client.out)
        self.assertIn("Hello World B Release!", client.out)
        self.assertIn("Hello World A Release!", client.out)

        # Now do the same for debug
        client.run("install . -s build_type=Debug")
        client.run("build C -bf=C/%s" % debug)
        client.run("build B -bf=B/%s" % debug)
        client.run("build A -bf=A/%s" % debug)
        client.runner(cmd_debug, cwd=client.current_folder)
        self.assertIn("Hello World C Debug!", client.out)
        self.assertIn("Hello World B Debug!", client.out)
        self.assertIn("Hello World A Debug!", client.out)
Beispiel #33
0
 def load(folder):
     text = load(os.path.join(folder, CONAN_MANIFEST))
     return FileTreeManifest.loads(text)
Beispiel #34
0
    def reuse_test(self):
        self._export_upload("Hello0", "0.1")
        self._export_upload("Hello00", "0.2", msg="#")
        self._export_upload("Hello1",
                            "0.1",
                            deps=[("Hello0/0.1@lasote/stable", "private")],
                            static=False)
        self._export_upload("Hello2",
                            "0.1",
                            deps=[("Hello00/0.2@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", "Hello2/0.1@lasote/stable"])

        # WE need to copy the DLLs and dylib
        client.save(files3)

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

        # assert Hello3 only depends on Hello2, and Hello1
        info_path = os.path.join(client.current_folder, BUILD_INFO_CMAKE)
        build_info_cmake = load(info_path)
        # 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', 'Hello Hello2',
            'Hello #'
        ],
                         str(client.user_io.out).splitlines()[-5:])

        # assert Hello3 only depends on Hello2, and Hello1
        info_path = os.path.join(client.current_folder, CONANINFO)
        conan_info = ConanInfo.loads(load(info_path))

        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)
        client.run("upload Hello2/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")]})
        files2 = cpp_hello_conan_files(
            "Hello3", "0.1",
            ["Hello1/0.1@lasote/stable", "Hello2/0.1@lasote/stable"])

        # WE need to copy the DLLs
        client2.save(files2)

        client2.run("install . --build missing")
        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("libhello00.a", client2.user_io.out)
        self.assertNotIn("libhello1.a", client2.user_io.out)
        self.assertNotIn("libhello2.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', 'Hello Hello2',
            'Hello #'
        ],
                         str(client2.user_io.out).splitlines()[-5:])
        files3 = cpp_hello_conan_files(
            "Hello3",
            "0.2", ["Hello1/0.1@lasote/stable", "Hello2/0.1@lasote/stable"],
            language=1)

        client2.save(files3)
        client2.run('install -o language=1 --build missing')
        client2.run('build')
        self.assertNotIn("libhello0.a", client2.user_io.out)
        self.assertNotIn("libhello00.a", client2.user_io.out)
        self.assertNotIn("libhello1.a", client2.user_io.out)
        self.assertNotIn("libhello2.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 Hello2',
            'Hola #'
        ],
                         str(client2.user_io.out).splitlines()[-5:])

        # Issue 79, fixing private deps from current project
        files3 = cpp_hello_conan_files(
            "Hello3",
            "0.2", [
                "Hello1/0.1@lasote/stable", "Hello2/0.1@lasote/stable",
                ("Hello0/0.1@lasote/stable", "private"),
                ("Hello00/0.2@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("libhello00.a", client2.user_io.out)
        self.assertNotIn("libhello1.a", client2.user_io.out)
        self.assertNotIn("libhello2.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 Hello2',
            'Hola #', 'Hola Hello0', 'Hola #'
        ],
                         str(client2.user_io.out).splitlines()[-7:])
Beispiel #35
0
 def default_compiler_visual_studio(self):
     text = load(self.paths.conan_conf_path)
     return "compiler=Visual Studio" in text
Beispiel #36
0
    def upload_test(self):
        conan_reference = ConanFileReference.loads("Hello0/0.1@lasote/stable")
        files = cpp_hello_conan_files("Hello0", "0.1")
        files["to_be_deleted.txt"] = "delete me"
        files["to_be_deleted2.txt"] = "delete me2"

        remote_paths = self.client.servers["default"].paths
        server_conan_path = remote_paths.export(conan_reference)

        self.client.save(files)
        self.client.run("export . lasote/stable")

        # Upload conan file
        self.client.run("upload %s" % str(conan_reference))

        # Verify the files are there
        self.assertTrue(
            os.path.exists(os.path.join(server_conan_path, EXPORT_TGZ_NAME)))
        tmp = temp_folder()
        untargz(os.path.join(server_conan_path, EXPORT_TGZ_NAME), tmp)
        self.assertTrue(load(os.path.join(tmp, "to_be_deleted.txt")),
                        "delete me")
        self.assertTrue(load(os.path.join(tmp, "to_be_deleted2.txt")),
                        "delete me2")

        # Now delete local files export and upload and check that they are not in server
        os.remove(os.path.join(self.client.current_folder,
                               "to_be_deleted.txt"))
        self.client.run("export . lasote/stable")
        self.client.run("upload %s" % str(conan_reference))
        self.assertTrue(
            os.path.exists(os.path.join(server_conan_path, EXPORT_TGZ_NAME)))
        tmp = temp_folder()
        untargz(os.path.join(server_conan_path, EXPORT_TGZ_NAME), tmp)
        self.assertFalse(os.path.exists(os.path.join(tmp,
                                                     "to_be_deleted.txt")))
        self.assertTrue(os.path.exists(os.path.join(tmp,
                                                    "to_be_deleted2.txt")))

        # Now modify a file, and delete other, and put a new one.
        files["to_be_deleted2.txt"] = "modified content"
        files["new_file.lib"] = "new file"
        del files["to_be_deleted.txt"]
        self.client.save(files)
        self.client.run("export . lasote/stable")
        self.client.run("upload %s" % str(conan_reference))

        # Verify all is correct
        self.assertTrue(
            os.path.exists(os.path.join(server_conan_path, EXPORT_TGZ_NAME)))
        tmp = temp_folder()
        untargz(os.path.join(server_conan_path, EXPORT_TGZ_NAME), tmp)
        self.assertTrue(load(os.path.join(tmp, "to_be_deleted2.txt")),
                        "modified content")
        self.assertTrue(load(os.path.join(tmp, "new_file.lib")), "new file")
        self.assertFalse(os.path.exists(os.path.join(tmp,
                                                     "to_be_deleted.txt")))

        ##########################
        # Now try with the package
        ##########################

        self.client.run("install %s --build missing" % str(conan_reference))
        # Upload package
        package_ids = self.client.paths.conan_packages(conan_reference)
        self.client.run("upload %s -p %s" %
                        (str(conan_reference), str(package_ids[0])))

        # Check that conans exists on server
        package_reference = PackageReference(conan_reference,
                                             str(package_ids[0]))
        package_server_path = remote_paths.package(package_reference)
        self.assertTrue(os.path.exists(package_server_path))

        # Add a new file to package (artificially), upload again and check
        pack_path = self.client.paths.package(package_reference)
        new_file_source_path = os.path.join(pack_path, "newlib.lib")
        save(new_file_source_path, "newlib")
        os.unlink(os.path.join(pack_path, PACKAGE_TGZ_NAME))  # Force new tgz

        self._create_manifest(package_reference)
        self.client.run("upload %s -p %s" %
                        (str(conan_reference), str(package_ids[0])))

        folder = uncompress_packaged_files(remote_paths, package_reference)
        remote_file_path = os.path.join(folder, "newlib.lib")
        self.assertTrue(os.path.exists(remote_file_path))

        # Now modify the file and check again
        save(new_file_source_path, "othercontent")
        self._create_manifest(package_reference)
        self.client.run("upload %s -p %s" %
                        (str(conan_reference), str(package_ids[0])))
        folder = uncompress_packaged_files(remote_paths, package_reference)
        remote_file_path = os.path.join(folder, "newlib.lib")
        self.assertTrue(os.path.exists(remote_file_path))
        self.assertTrue(load(remote_file_path), "othercontent")

        # Now delete the file and check again
        os.remove(new_file_source_path)
        self._create_manifest(package_reference)
        os.unlink(os.path.join(pack_path, PACKAGE_TGZ_NAME))  # Force new tgz
        self.client.run("upload %s -p %s" %
                        (str(conan_reference), str(package_ids[0])))
        folder = uncompress_packaged_files(remote_paths, package_reference)
        remote_file_path = os.path.join(folder, "newlib.lib")

        self.assertFalse(os.path.exists(remote_file_path))
        self.assertNotEquals(remote_file_path, new_file_source_path)
Beispiel #37
0
    def conan_test_test(self):
        '''Checks --build in test command'''

        client = TestClient(servers=self.servers,
                            users={"default": [("lasote", "mypass")]})
        self._create(client, "Hello0", "0.0")
        self._create(client, "Hello1", "1.1", ["Hello0/0.0@lasote/stable"])

        # Now test out Hello2
        self._create(client,
                     "Hello2",
                     "2.2", ["Hello1/1.1@lasote/stable"],
                     export=True)
        hello2conanfile = load(os.path.join(client.current_folder, CONANFILE))
        client.save({CONANFILE: hello2conanfile})

        test_conanfile = '''
from conans.model.conan_file import ConanFile

class DefaultNameConan(ConanFile):
    settings = "os", "compiler", "arch"
    requires = "Hello2/2.2@lasote/stable"
    generators = "cmake"

    def test(self):
        pass
        '''
        client.save({"test/%s" % CONANFILE: test_conanfile})

        # Should recognize the hello package
        # Will Fail because Hello0/0.0 and Hello1/1.1 has not built packages
        # and by default no packages are built
        error = client.run("test", ignore_error=True)
        self.assertTrue(error)
        self.assertIn('Try to build it from sources with "--build Hello0"',
                      client.user_io.out)

        # We generate the package for Hello0/0.0
        client.run("install Hello0/0.0@lasote/stable --build Hello0")

        # Still missing Hello1/1.1
        error = client.run("test", ignore_error=True)
        self.assertTrue(error)
        self.assertIn('Try to build it from sources with "--build Hello1"',
                      client.user_io.out)

        # We generate the package for Hello1/1.1
        client.run("install Hello1/1.1@lasote/stable --build Hello1")

        # Now Hello2 should be built and not fail
        client.run("test")
        self.assertNotIn("Can't find a 'Hello2/2.2@lasote/stable' package",
                         client.user_io.out)
        self.assertIn(
            'Hello2/2.2@lasote/stable: WARN: Forced build from source',
            client.user_io.out)

        # Now package is generated but should be built again
        client.run("test")
        self.assertIn(
            'Hello2/2.2@lasote/stable: WARN: Forced build from source',
            client.user_io.out)
Beispiel #38
0
 def load_metadata(self):
     try:
         text = load(self.package_metadata())
     except IOError:
         raise RecipeNotFoundException(self._ref)
     return PackageMetadata.loads(text)
Beispiel #39
0
 def settings(self):
     """Returns {setting: [value, ...]} defining all the possible
        settings without values"""
     self.initialize_settings()
     content = load(self.settings_path)
     return Settings.loads(content)
Beispiel #40
0
    def _make_migrations(self, old_version):
        # ############### FILL THIS METHOD WITH THE REQUIRED ACTIONS ##############
        # VERSION 0.1
        if old_version is None:
            return
        if old_version < Version("0.3"):
            self.out.warn(
                "Migration: Reseting configuration and storage files...")
            if os.path.exists(self.conf_path):
                rmdir(self.conf_path)
            if os.path.exists(self.store_path):
                rmdir(self.store_path)
        elif old_version < Version("0.5"):
            self.out.warn(
                "Migration: Updating settings.yml with new gcc versions")
            default_settings = load(self.paths.settings_path)
            default_settings = default_settings.replace(
                'version: ["4.6", "4.7", "4.8", "4.9", "5.0"]',
                'version: ["4.6", "4.7", "4.8", "4.9", "5.1", "5.2", "5.3"]')
            save(self.paths.settings_path, default_settings)
        elif old_version < Version("0.7"):
            old_settings = """
os: [Windows, Linux, Macos, Android]
arch: [x86, x86_64, armv]
compiler:
    gcc:
        version: ["4.6", "4.7", "4.8", "4.9", "5.1", "5.2", "5.3"]
    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"]
    apple-clang:
        version: ["5.0", "5.1", "6.0", "6.1", "7.0"]

build_type: [None, Debug, Release]
"""
            self._update_settings_yml(old_settings)
        elif old_version < Version("0.8"):
            self.out.info("**** Migrating to conan 0.8 *****")
            settings_backup_path = self.paths.settings_path + ".backup"
            save(settings_backup_path, load(self.paths.settings_path))
            # Save new settings
            save(self.paths.settings_path, default_settings_yml)
            self.out.info("- A new settings.yml has been defined")
            self.out.info("  Your old file has been backup'd to: %s" %
                          settings_backup_path)

            old_conanconf = load(self.paths.conan_conf_path)
            conf = dict(self.paths.conan_config.get_conf("settings_defaults"))
            if conf.get("os", None) in ("Linux", "Macos") and \
               conf.get("compiler", None) in ("gcc", "clang", "apple-clang"):

                # Backup the old config and append the new setting
                config_backup_path = self.paths.conan_conf_path + ".backup"
                save(config_backup_path, old_conanconf)
                new_setting = "libstdc++"
                if conf.get("compiler", None) == "apple-clang":
                    new_setting = "libc++"
                self.paths.conan_config.set("settings_defaults",
                                            "compiler.libcxx", new_setting)
                with open(self.paths.conan_conf_path, 'wb') as configfile:
                    self.paths.conan_config.write(configfile)

                self.out.info("- A new conan.conf has been defined")
                self.out.info("  Your old file has been backup'd to: %s" %
                              config_backup_path)

                self.out.info("- Reseting storage files...")
                if os.path.exists(self.store_path):
                    rmdir(self.store_path)

                # Print information about new setting
                self.out.warn("{0:s} IMPORTANT {0:s}".format("*" * 30))
                self.out.warn(
                    "Conan 0.8 have a new setting for your compiler: 'compiler.libcxx' "
                )
                self.out.warn(
                    "It defines the Standard C++ Library and it's ABI (C99 or C++11)"
                )
                if new_setting == "libstdc++":
                    self.out.warn(
                        "By default, and to keep the higher compatibility in your packages, we setted this setting value to 'libstdc++'"
                    )
                    self.out.warn(
                        "If you are using C++11 features or you want to use the gcc>5.1 ABI, set this setting to 'libstdc++11' "
                    )
                self.out.warn(
                    "If you uploaded some packages it's needed that you regenerate them, conan will set the new setting automatically"
                )
                self.out.warn(
                    "If your packages are written in pure 'C' language, you should deactivate this setting for your package adding this line to your conanfile.py config method:"
                )
                self.out.info(" ")
                self.out.info(" def config(self):")
                self.out.info("     del self.settings.compiler.libcxx")
                self.out.info(" ")
                self.out.warn(
                    "Your local storage has been deleted, perform a 'conan install' in your projects to restore them."
                )
                self.out.warn(
                    "You can read more information about this new setting and how to adapt your packages here: http://blog.conan.io/"
                )
                self.out.warn("*" * 71)
                self.out.info("   ")
        elif old_version < Version("0.8.3"):
            self.out.warn(
                "Migration: Updating settings.yml with new Apple clang 7.3 version"
            )
            default_settings = load(self.paths.settings_path)
            default_settings = default_settings.replace(
                'version: ["5.0", "5.1", "6.0", "6.1", "7.0"]',
                'version: ["5.0", "5.1", "6.0", "6.1", "7.0", "7.3"]')
            save(self.paths.settings_path, default_settings)
        elif old_version < Version("0.10"):
            old_settings = """
os: [Windows, Linux, Macos, Android, iOS]
arch: [x86, x86_64, armv6, armv7, armv7hf, armv8]
compiler:
    gcc:
        version: ["4.4", "4.5", "4.6", "4.7", "4.8", "4.9", "5.1", "5.2", "5.3", "6.1"]
        libcxx: [libstdc++, libstdc++11]
    Visual Studio:
        runtime: [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.3"]
        libcxx: [libstdc++, libc++]

build_type: [None, Debug, Release]
"""
            self._update_settings_yml(old_settings)
Beispiel #41
0
    def pkg_config_dirs_test(self):
        # https://github.com/conan-io/conan/issues/2756
        conanfile = """
import os
from conans import ConanFile

class PkgConfigConan(ConanFile):
    name = "MyLib"
    version = "0.1"

    def package_info(self):
        self.cpp_info.includedirs = []
        self.cpp_info.libdirs = []
        self.cpp_info.bindirs = []
        self.cpp_info.libs = []
        libname = "mylib"
        fake_dir = os.path.join("/", "my_absoulte_path", "fake")
        include_dir = os.path.join(fake_dir, libname, "include")
        lib_dir = os.path.join(fake_dir, libname, "lib")
        lib_dir2 = os.path.join(self.package_folder, "lib2")
        self.cpp_info.includedirs.append(include_dir)
        self.cpp_info.libdirs.append(lib_dir)
        self.cpp_info.libdirs.append(lib_dir2)
"""
        client = TestClient()
        client.save({"conanfile.py": conanfile})
        client.run("create . danimtb/testing")
        client.run("install MyLib/0.1@danimtb/testing -g pkg_config")

        pc_path = os.path.join(client.current_folder, "MyLib.pc")
        self.assertTrue(os.path.exists(pc_path))
        pc_content = load(pc_path)
        expected_rpaths = ""
        if platform.system() == "Linux":
            expected_rpaths = ' -Wl,-rpath="${libdir}" -Wl,-rpath="${libdir3}"'
        elif platform.system() == "Darwin":
            expected_rpaths = ' -Wl,-rpath,"${libdir}" -Wl,-rpath,"${libdir3}"'
        expected_content = """libdir=/my_absoulte_path/fake/mylib/lib
libdir2=${prefix}/lib2
includedir=/my_absoulte_path/fake/mylib/include

Name: MyLib
Description: Conan package: MyLib
Version: 0.1
Libs: -L${libdir} -L${libdir2}%s
Cflags: -I${includedir}""" % expected_rpaths
        self.assertEqual("\n".join(pc_content.splitlines()[1:]),
                         expected_content)

        def assert_is_abs(path):
            self.assertTrue(os.path.isabs(path))

        for line in pc_content.splitlines():
            if line.startswith("includedir="):
                assert_is_abs(line[len("includedir="):])
                self.assertTrue(line.endswith("include"))
            elif line.startswith("libdir="):
                assert_is_abs(line[len("libdir="):])
                self.assertTrue(line.endswith("lib"))
            elif line.startswith("libdir3="):
                self.assertIn("${prefix}/lib2", line)
Beispiel #42
0
    def test_replace_paths(self):
        folder = temp_folder()
        path = os.path.join(folder, "file")
        replace_with = "MYPATH"
        expected = 'Some other contentsMYPATH"finally all text'

        out = TestBufferConanOutput()
        save(path,
             'Some other contentsc:\\Path\\TO\\file.txt"finally all text')
        ret = tools.replace_path_in_file(path,
                                         "C:/Path/to/file.txt",
                                         replace_with,
                                         windows_paths=True,
                                         output=out)
        self.assertEqual(load(path), expected)
        self.assertTrue(ret)

        save(path, 'Some other contentsC:/Path\\TO\\file.txt"finally all text')
        ret = tools.replace_path_in_file(path,
                                         "C:/PATH/to/FILE.txt",
                                         replace_with,
                                         windows_paths=True,
                                         output=out)
        self.assertEqual(load(path), expected)
        self.assertTrue(ret)

        save(path, 'Some other contentsD:/Path\\TO\\file.txt"finally all text')
        ret = tools.replace_path_in_file(path,
                                         "C:/PATH/to/FILE.txt",
                                         replace_with,
                                         strict=False,
                                         windows_paths=True,
                                         output=out)
        self.assertEqual(
            load(path),
            'Some other contentsD:/Path\\TO\\file.txt"finally all text')
        self.assertFalse(ret)

        # Multiple matches
        s = 'Some other contentsD:/Path\\TO\\file.txt"finally all textd:\\PATH\\to\\file.TXTMoretext'
        save(path, s)
        ret = tools.replace_path_in_file(path,
                                         "D:/PATH/to/FILE.txt",
                                         replace_with,
                                         strict=False,
                                         windows_paths=True,
                                         output=out)
        self.assertEqual(
            load(path),
            'Some other contentsMYPATH"finally all textMYPATHMoretext')
        self.assertTrue(ret)

        # Automatic windows_paths
        save(path, s)
        ret = tools.replace_path_in_file(path,
                                         "D:/PATH/to/FILE.txt",
                                         replace_with,
                                         strict=False,
                                         output=out)
        if platform.system() == "Windows":
            self.assertEqual(
                load(path),
                'Some other contentsMYPATH"finally all textMYPATHMoretext')
            self.assertTrue(ret)
        else:
            self.assertFalse(ret)
Beispiel #43
0
    def basic_test(self, python_consumer):
        client = TestClient()

        client.save({"conanfile.py": conanfile})
        client.run("export . user/channel")
        if python_consumer:
            client.save({"conanfile.py": consumer_py}, clean_first=True)
        else:
            client.save({"conanfile.txt": consumer}, clean_first=True)
        # Windows Debug
        client.run('install . -s os=Windows -s build_type=Debug')
        self.assertIn(
            "Building package from source as defined by build_policy='missing'",
            client.user_io.out)
        self.assertIn("Building my code!", client.user_io.out)
        self.assertIn("Packaging Debug!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Debug file1", content)
        # Package Windows Release, it will reuse the previous build
        client.run('install . -s os=Windows -s build_type=Release')
        self.assertNotIn("Building my code!", client.user_io.out)
        self.assertIn("Packaging Release!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Release file1", content)

        # Now Linux Debug
        client.run('install . -s os=Linux -s build_type=Debug')
        self.assertIn(
            "Building package from source as defined by build_policy='missing'",
            client.user_io.out)
        self.assertIn("Building my code!", client.user_io.out)
        self.assertIn("Packaging Debug!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Debug file1", content)
        # Linux Release must build again, as it is not affected by build_id()
        client.run('install . -s os=Linux -s build_type=Release')
        self.assertIn("Building my code!", client.user_io.out)
        self.assertIn("Packaging Release!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Release file1", content)
        self._check_conaninfo(client)

        # Check that repackaging works, not necessary to re-build
        client.run("remove Pkg/0.1@user/channel -p -f")
        # Windows Debug
        client.run('install . -s os=Windows -s build_type=Debug')
        self.assertNotIn("Building my code!", client.user_io.out)
        self.assertIn("Packaging Debug!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Debug file1", content)
        # Windows Release
        client.run('install . -s os=Windows -s build_type=Release')
        self.assertNotIn("Building my code!", client.user_io.out)
        self.assertIn("Packaging Release!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Release file1", content)
        # Now Linux
        client.run('install . -s os=Linux -s build_type=Debug')
        self.assertIn(
            "Building package from source as defined by build_policy='missing'",
            client.user_io.out)
        self.assertIn("Building my code!", client.user_io.out)
        self.assertIn("Packaging Debug!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Debug file1", content)
        client.run('install . -s os=Linux -s build_type=Release')
        self.assertIn("Building my code!", client.user_io.out)
        self.assertIn("Packaging Release!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Release file1", content)
        self._check_conaninfo(client)

        # But if the build folder is removed, the packages are there, do nothing
        client.run("remove Pkg/0.1@user/channel -b -f")
        client.run('install . -s os=Windows -s build_type=Debug')
        self.assertNotIn("Building my code!", client.user_io.out)
        self.assertNotIn("Packaging Debug!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Debug file1", content)
        client.run('install . -s os=Windows -s build_type=Release')
        self.assertNotIn("Building my code!", client.user_io.out)
        self.assertNotIn("Packaging Release!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Release file1", content)
        # Now Linux
        client.run('install . -s os=Linux -s build_type=Debug')
        self.assertNotIn("Building my code!", client.user_io.out)
        self.assertNotIn("Packaging Debug!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Debug file1", content)
        client.run('install . -s os=Linux -s build_type=Release')
        self.assertNotIn("Building my code!", client.user_io.out)
        self.assertNotIn("Packaging Release!", client.user_io.out)
        content = load(os.path.join(client.current_folder, "file1.txt"))
        self.assertEqual("Release file1", content)
        self._check_conaninfo(client)
Beispiel #44
0
 def test_load_save(self):
     folder = temp_folder()
     path = os.path.join(folder, "file")
     save(path, u"äüïöñç")
     content = load(path)
     self.assertEqual(content, u"äüïöñç")
Beispiel #45
0
 def timestamps():
     recipe_timestamp = load(recipe_manifest).splitlines()[0]
     package_timestamp = load(package_manifest).splitlines()[0]
     return recipe_timestamp, package_timestamp
Beispiel #46
0
    def user_properties_multifile_test(self):
        conan_build_vs = textwrap.dedent("""
            from conans import ConanFile, MSBuild

            class HelloConan(ConanFile):
                exports = "*"
                settings = "os", "build_type", "arch", "compiler"

                def build(self):
                    msbuild = MSBuild(self)
                    msbuild.build("MyProject.sln", verbosity="normal",
                                  definitions={"MyCustomDef": "MyCustomValue"},
                                  user_property_file_name=["myuser.props", "myuser2.props"])

                def package(self):
                    self.copy(pattern="*.exe")
            """)
        client = TestClient()

        files = get_vs_project_files()
        files[CONANFILE] = conan_build_vs
        props = textwrap.dedent("""<?xml version="1.0" encoding="utf-8"?>
            <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
              <ImportGroup Label="PropertySheets" />
              <PropertyGroup Label="UserMacros" />
              <ItemDefinitionGroup>
                <ClCompile>
                    <PreprocessorDefinitions>MyCustomDef2=MyValue2;%(PreprocessorDefinitions)
                    </PreprocessorDefinitions>
                </ClCompile>
              </ItemDefinitionGroup>
              <ItemGroup />
            </Project>
            """)
        props2 = textwrap.dedent("""<?xml version="1.0" encoding="utf-8"?>
            <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
              <ImportGroup Label="PropertySheets" />
              <PropertyGroup Label="UserMacros" />
              <ItemDefinitionGroup>
                <ClCompile>
                  <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
                </ClCompile>
              </ItemDefinitionGroup>
              <ItemGroup />
            </Project>
            """)
        files["myuser.props"] = props
        files["myuser2.props"] = props2

        client.save(files)
        client.run('create . Hello/1.2.1@lasote/stable')
        self.assertNotIn("/EHsc /MD", client.out)
        self.assertIn("/EHsc /MT", client.out)
        self.assertIn("/D MyCustomDef=MyCustomValue", client.out)
        self.assertIn("/D MyCustomDef2=MyValue2", client.out)
        self.assertIn("Packaged 1 '.exe' file: MyProject.exe", client.out)

        full_ref = "Hello/1.2.1@lasote/stable:6cc50b139b9c3d27b3e9042d5f5372d327b3a9f7"
        pref = PackageReference.loads(full_ref)
        build_folder = client.cache.package_layout(pref.ref).build(pref)
        self.assertTrue(
            os.path.exists(os.path.join(build_folder, "myuser.props")))
        conan_props = os.path.join(build_folder, "conan_build.props")
        content = load(conan_props)
        self.assertIn("<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>",
                      content)
Beispiel #47
0
 def conaninfo(self):
     return load(os.path.join(self.client.current_folder, CONANINFO))
Beispiel #48
0
    def basic_test(self, posix_empty_vars=True):
        env = copy.deepcopy(os.environ)
        client = TestClient()
        dep1 = """
import os
from conans import ConanFile

class BaseConan(ConanFile):
    name = "base"
    version = "0.1"

    def package_info(self):
        self.env_info.PATH.extend([os.path.join("basedir", "bin"),"samebin"])
        self.env_info.LD_LIBRARY_PATH.append(os.path.join("basedir", "lib"))
        self.env_info.BASE_VAR = "baseValue"
        self.env_info.SPECIAL_VAR = "baseValue"
        self.env_info.BASE_LIST = ["baseValue1", "baseValue2"]
        self.env_info.CPPFLAGS = ["-baseFlag1", "-baseFlag2"]
        self.env_info.BCKW_SLASH = r"base\\value"
"""

        dep2 = """
import os
from conans import ConanFile

class DummyConan(ConanFile):
    name = "dummy"
    version = "0.1"
    requires = "base/0.1@lasote/testing"

    def package_info(self):
        self.env_info.PATH = [os.path.join("dummydir", "bin"),"samebin"]
        self.env_info.LD_LIBRARY_PATH.append(os.path.join("dummydir", "lib"))
        self.env_info.SPECIAL_VAR = "dummyValue"
        self.env_info.BASE_LIST = ["dummyValue1", "dummyValue2"]
        self.env_info.CPPFLAGS = ["-flag1", "-flag2"]
        self.env_info.BCKW_SLASH = r"dummy\\value"
"""
        base = '''
[requires]
dummy/0.1@lasote/testing
[generators]
virtualenv
    '''
        client.save({"conanfile.py": dep1})
        client.run("export . lasote/testing")
        client.save({"conanfile.py": dep2}, clean_first=True)
        client.run("export . lasote/testing")
        client.save({"conanfile.txt": base}, clean_first=True)
        client.run("install . --build")

        os_info = OSInfo()
        if os_info.is_windows and not os_info.is_posix:
            activate = load(os.path.join(client.current_folder,
                                         "activate.bat"))
            self.assertIn('SET PROMPT=(conanenv) %PROMPT%', activate)
            self.assertIn(
                'SET BASE_LIST=dummyValue1;dummyValue2;baseValue1;baseValue2;%BASE_LIST%',
                activate)
            self.assertIn('SET BASE_VAR=baseValue', activate)
            self.assertIn(
                'SET CPPFLAGS=-flag1 -flag2 -baseFlag1 -baseFlag2 %CPPFLAGS%',
                activate)
            self.assertIn(
                'SET LD_LIBRARY_PATH=dummydir\\lib;basedir\\lib;%LD_LIBRARY_PATH%',
                activate)
            self.assertIn('SET PATH=dummydir\\bin;basedir\\bin;samebin;%PATH%',
                          activate)
            self.assertIn('SET SPECIAL_VAR=dummyValue', activate)
            self.assertIn('SET BCKW_SLASH=dummy\\value', activate)

            activate = load(os.path.join(client.current_folder,
                                         "activate.ps1"))
            self.assertIn(
                '$env:BASE_LIST = "dummyValue1;dummyValue2;baseValue1;baseValue2;$env:BASE_LIST"',
                activate)
            self.assertIn('$env:BASE_VAR = "baseValue"', activate)
            self.assertIn(
                '$env:CPPFLAGS = "-flag1 -flag2 -baseFlag1 -baseFlag2 $env:CPPFLAGS"',
                activate)
            self.assertIn(
                '$env:LD_LIBRARY_PATH = "dummydir\\lib;basedir\\lib;$env:LD_LIBRARY_PATH"',
                activate)
            self.assertIn(
                '$env:PATH = "dummydir\\bin;basedir\\bin;samebin;$env:PATH"',
                activate)
            self.assertIn('$env:SPECIAL_VAR = "dummyValue"', activate)
            self.assertIn('$env:BCKW_SLASH = "dummy\\value"', activate)

            deactivate = load(
                os.path.join(client.current_folder, "deactivate.bat"))
            self.assertIn('SET PROMPT=%s' % env.setdefault('PROMPT', ''),
                          deactivate)
            self.assertIn('SET BASE_LIST=%s' % env.setdefault('BASE_LIST', ''),
                          deactivate)
            self.assertIn('SET BASE_VAR=%s' % env.setdefault('BASE_VAR', ''),
                          deactivate)
            self.assertIn('SET CPPFLAGS=%s' % env.setdefault('CPPFLAGS', ''),
                          deactivate)
            self.assertIn(
                'SET LD_LIBRARY_PATH=%s' %
                env.setdefault('LD_LIBRARY_PATH', ''), deactivate)
            self.assertIn('SET PATH=%s' % env.setdefault('PATH', ''),
                          deactivate)
            self.assertIn(
                'SET SPECIAL_VAR=%s' % env.setdefault('SPECIAL_VAR', ''),
                deactivate)
            self.assertIn(
                'SET BCKW_SLASH=%s' % env.setdefault('BCKW_SLASH', ''),
                deactivate)

            deactivate = load(
                os.path.join(client.current_folder, "deactivate.ps1"))
            self.assertIn(
                '$env:BASE_LIST = "%s"' % env.setdefault('BASE_LIST', ''),
                deactivate)
            self.assertIn(
                '$env:BASE_VAR = "%s"' % env.setdefault('BASE_VAR', ''),
                deactivate)
            self.assertIn(
                '$env:CPPFLAGS = "%s"' % env.setdefault('CPPFLAGS', ''),
                deactivate)
            self.assertIn(
                '$env:LD_LIBRARY_PATH = "%s"' %
                env.setdefault('LD_LIBRARY_PATH', ''), deactivate)
            self.assertIn('$env:PATH = "%s"' % env.setdefault('PATH', ''),
                          deactivate)
            self.assertIn(
                '$env:SPECIAL_VAR = "%s"' % env.setdefault('SPECIAL_VAR', ''),
                deactivate)
            self.assertIn(
                '$env:BCKW_SLASH = "%s"' % env.setdefault('BCKW_SLASH', ''),
                deactivate)

        activate = load(os.path.join(client.current_folder, "activate.sh"))
        self.assertIn('OLD_PS1="$PS1"', activate)
        self.assertIn('export OLD_PS1', activate)
        self.assertIn('PS1="(conanenv) $PS1"', activate)
        self.assertIn('export PS1', activate)
        self.assertIn(
            'BASE_LIST="dummyValue1":"dummyValue2":"baseValue1":"baseValue2"${'
            'BASE_LIST+:$BASE_LIST}', activate)
        self.assertIn('export BASE_LIST', activate)
        self.assertIn('BASE_VAR="baseValue"', activate)
        self.assertIn('export BASE_VAR', activate)
        self.assertIn(
            'CPPFLAGS="-flag1 -flag2 -baseFlag1 -baseFlag2 ${CPPFLAGS+ $CPPFLAGS}"',
            activate)
        self.assertIn('export CPPFLAGS', activate)
        self.assertIn('SPECIAL_VAR="dummyValue"', activate)
        self.assertIn('export SPECIAL_VAR', activate)
        self.assertIn('BCKW_SLASH="dummy\\value"', activate)
        self.assertIn('export BCKW_SLASH', activate)
        if os_info.is_windows:
            self.assertIn(
                'LD_LIBRARY_PATH="dummydir\\lib":"basedir\\lib"${'
                'LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}', activate)
            self.assertIn(
                'PATH="dummydir\\bin":"basedir\\bin":"samebin"${PATH+:$PATH}',
                activate)
        else:
            self.assertIn(
                'LD_LIBRARY_PATH="dummydir/lib":"basedir/lib"${'
                'LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}', activate)
            self.assertIn(
                'PATH="dummydir/bin":"basedir/bin":"samebin"${PATH+:$PATH}',
                activate)
        self.assertIn('export LD_LIBRARY_PATH', activate)
        self.assertIn('export PATH', activate)
        deactivate = load(os.path.join(client.current_folder, "deactivate.sh"))
        if posix_empty_vars:
            self.assertNotIn('unset PS1', deactivate)
            self.assertIn('unset OLD_PS1', deactivate)
            self.assertIn('unset BASE_LIST', deactivate)
            self.assertIn('unset BASE_VAR', deactivate)
            self.assertIn('unset CPPFLAGS', deactivate)
            self.assertIn('unset LD_LIBRARY_PATH', deactivate)
            self.assertIn('PATH="%s"' % env.setdefault('PATH', ''), deactivate)
            self.assertIn('export PATH', deactivate)
            self.assertIn('unset SPECIAL_VAR', deactivate)
            self.assertIn('unset BCKW_SLASH', deactivate)
        else:
            self.assertIn('OLD_PS1="%s"' % env.setdefault('OLD_PS1', ''),
                          deactivate)
            self.assertIn('PS1=$OLD_PS1', deactivate)
            self.assertIn('export OLD_PS1', deactivate)
            self.assertNotIn('PS1="%s"' % env.setdefault('PS1', ''),
                             deactivate)
            self.assertIn('export PS1', deactivate)
            self.assertIn('BASE_LIST="%s"' % env.setdefault('BASE_LIST', ''),
                          deactivate)
            self.assertIn('export BASE_LIST', deactivate)
            self.assertIn('BASE_VAR="%s"' % env.setdefault('BASE_VAR', ''),
                          deactivate)
            self.assertIn('export BASE_VAR', deactivate)
            self.assertIn('CPPFLAGS="%s"' % env.setdefault('CPPFLAGS', ''),
                          deactivate)
            self.assertIn('export CPPFLAGS', deactivate)
            self.assertIn(
                'LD_LIBRARY_PATH="%s"' % env.setdefault('LD_LIBRARY_PATH', ''),
                deactivate)
            self.assertIn('export LD_LIBRARY_PATH', deactivate)
            self.assertIn('PATH="%s"' % env.setdefault('PATH', ''), deactivate)
            self.assertIn('export PATH', deactivate)
            self.assertIn(
                'SPECIAL_VAR="%s"' % env.setdefault('SPECIAL_VAR', ''),
                deactivate)
            self.assertIn('export SPECIAL_VAR', deactivate)
            self.assertIn('BCKW_SLASH="%s"' % env.setdefault('BCKW_SLASH', ''),
                          deactivate)
            self.assertIn('export BCKW_SLASH', deactivate)
Beispiel #49
0
    def test_native_export_multi(self):
        """
        bye depends on hello. Both use find_package in their CMakeLists.txt
        The consumer depends on bye, using the cmake_find_package_multi generator
        """
        c = TestClient()
        project_folder_name = "project_targets"
        assets_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                   "assets/cmake_find_package_multi")
        c.copy_from_assets(assets_path, ["bye", "hello", project_folder_name])

        # Create packages for hello and bye
        for p in ("hello", "bye"):
            for bt in ("Debug", "Release"):
                c.run("create {} user/channel -s build_type={}".format(p, bt))

        with c.chdir(project_folder_name):
            # Save conanfile and example
            conanfile = textwrap.dedent("""
                [requires]
                bye/1.0@user/channel

                [generators]
                cmake_find_package_multi
                """)
            example_cpp = textwrap.dedent("""
                #include <iostream>
                #include "bye.h"

                int main() {
                    bye();
                }
                """)
            c.save({"conanfile.txt": conanfile, "example.cpp": example_cpp})

            with c.chdir("build"):
                for bt in ("Debug", "Release"):
                    c.run(
                        "install .. user/channel -s build_type={}".format(bt))

                # Test that we are using find_dependency with the NO_MODULE option
                # to skip finding first possible FindBye somewhere
                self.assertIn(
                    "find_dependency(hello REQUIRED NO_MODULE)",
                    load(os.path.join(c.current_folder, "byeConfig.cmake")))

                if platform.system() == "Windows":
                    c.run_command('cmake .. -G "Visual Studio 15 Win64"')
                    c.run_command('cmake --build . --config Debug')
                    c.run_command('cmake --build . --config Release')

                    c.run_command('Debug\\example.exe')
                    self.assertIn("Hello World Debug!", c.out)
                    self.assertIn("bye World Debug!", c.out)

                    c.run_command('Release\\example.exe')
                    self.assertIn("Hello World Release!", c.out)
                    self.assertIn("bye World Release!", c.out)
                else:
                    for bt in ("Debug", "Release"):
                        c.run_command(
                            'cmake .. -DCMAKE_BUILD_TYPE={}'.format(bt))
                        c.run_command('cmake --build .')
                        c.run_command('./example')
                        self.assertIn("Hello World {}!".format(bt), c.out)
                        self.assertIn("bye World {}!".format(bt), c.out)
                        os.remove(os.path.join(c.current_folder, "example"))
    def test_build_settings(self):
        def install_and_get_info(package_id_text):
            self.client.run("remove * -f")
            self._export("Hello",
                         "1.2.0",
                         package_id_text=package_id_text,
                         channel="user/testing",
                         settings=["os", "os_build", "arch", "arch_build"])
            self.client.run('install Hello/1.2.0@user/testing '
                            ' -s os="Windows" '
                            ' -s os_build="Linux"'
                            ' -s arch="x86_64"'
                            ' -s arch_build="x86"'
                            ' --build missing')

            hello_ref = ConanFileReference.loads("Hello/1.2.0@user/testing")
            layout = self.client.cache.package_layout(hello_ref)
            pkg_ids = layout.package_ids()
            hello_pref = PackageReference(hello_ref, pkg_ids[0])
            return ConanInfo.loads(
                load(os.path.join(layout.package(hello_pref), CONANINFO)))

        info = install_and_get_info(None)  # Default

        self.assertEqual(str(info.settings.os_build), "None")
        self.assertEqual(str(info.settings.arch_build), "None")

        # Package has to be present with only os and arch settings
        self.client.run('install Hello/1.2.0@user/testing '
                        ' -s os="Windows" '
                        ' -s arch="x86_64"')

        # Even with wrong build settings
        self.client.run('install Hello/1.2.0@user/testing '
                        ' -s os="Windows" '
                        ' -s arch="x86_64"'
                        ' -s os_build="Macos"'
                        ' -s arch_build="x86_64"')

        # take into account build
        info = install_and_get_info("self.info.include_build_settings()")
        self.assertEqual(str(info.settings.os_build), "Linux")
        self.assertEqual(str(info.settings.arch_build), "x86")

        # Now the build settings matter
        err = self.client.run(
            'install Hello/1.2.0@user/testing '
            ' -s os="Windows" '
            ' -s arch="x86_64"'
            ' -s os_build="Macos"'
            ' -s arch_build="x86_64"',
            assert_error=True)
        self.assertTrue(err)
        self.assertIn("Can't find", self.client.out)

        self.client.run('install Hello/1.2.0@user/testing '
                        ' -s os="Windows" '
                        ' -s arch="x86_64"'
                        ' -s os_build="Linux"'
                        ' -s arch_build="x86"')

        # Now only settings for build
        self.client.run("remove * -f")
        self._export("Hello",
                     "1.2.0",
                     channel="user/testing",
                     settings=["os_build", "arch_build"])
        self.client.run('install Hello/1.2.0@user/testing '
                        ' -s os_build="Linux"'
                        ' -s arch_build="x86"'
                        ' --build missing')
        ref = ConanFileReference.loads("Hello/1.2.0@user/testing")
        pkg = os.listdir(self.client.cache.package_layout(ref).packages())
        pref = PackageReference(ref, pkg[0])
        pkg_folder = self.client.cache.package_layout(pref.ref).package(pref)
        info = ConanInfo.loads(load(os.path.join(pkg_folder, CONANINFO)))
        self.assertEqual(str(info.settings.os_build), "Linux")
        self.assertEqual(str(info.settings.arch_build), "x86")
Beispiel #51
0
def _replace_scm_data_in_conanfile(conanfile_path, scm_data):
    # FIXME: Remove in Conan 2.0, it will use conandata.yml as the only way
    # Parsing and replacing the SCM field
    content = load(conanfile_path)
    headers = []

    if six.PY2:
        # Workaround for https://bugs.python.org/issue22221
        lines_without_headers = []
        lines = content.splitlines(True)
        for line in lines:
            if not lines_without_headers and line.startswith("#"):
                headers.append(line)
            else:
                lines_without_headers.append(line)
        content = ''.join(lines_without_headers)

    lines = content.splitlines(True)
    tree = ast.parse(content)
    to_replace = []
    comments = []
    class_line = None
    tab_size = 4
    for i_body, item in enumerate(tree.body):
        if isinstance(item, ast.ClassDef):
            statements = item.body
            class_line = item.lineno
            for i, stmt in enumerate(item.body):
                if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1:
                    line = lines[stmt.lineno - 1]
                    tab_size = len(line) - len(line.lstrip())
                    if isinstance(stmt.targets[0],
                                  ast.Name) and stmt.targets[0].id == "scm":
                        try:
                            if i + 1 == len(statements
                                            ):  # Last statement in my ClassDef
                                if i_body + 1 == len(
                                        tree.body):  # Last statement over all
                                    next_line = len(lines)
                                else:
                                    next_line = tree.body[i_body +
                                                          1].lineno - 1
                            else:
                                # Next statement can be a comment or anything else
                                next_statement = statements[i + 1]
                                if isPY38 and isinstance(
                                        next_statement, ast.Expr):
                                    # Python 3.8 properly parses multiline comments with start
                                    # and end lines, here we preserve the same (wrong)
                                    # implementation of previous releases
                                    next_line = next_statement.end_lineno - 1
                                else:
                                    next_line = next_statement.lineno - 1
                                next_line_content = lines[next_line].strip()
                                if (next_line_content.endswith('"""')
                                        or next_line_content.endswith("'''")):
                                    next_line += 1
                        except IndexError:
                            next_line = stmt.lineno
                        replace = [
                            line for line in lines[(stmt.lineno - 1):next_line]
                        ]
                        to_replace.append("".join(replace).lstrip())
                        comments = [
                            line.strip('\n') for line in replace if
                            line.strip().startswith("#") or not line.strip()
                        ]
                        break

    if len(to_replace) > 1:
        raise ConanException(
            "The conanfile.py defines more than one class level 'scm' attribute"
        )

    new_text = "scm = " + ",\n          ".join(str(scm_data).split(",")) + "\n"

    if len(to_replace) == 0:
        # SCM exists, but not found in the conanfile, probably inherited from superclass
        # FIXME: This will inject the lines only the latest class declared in the conanfile
        tmp = lines[0:class_line]
        tmp.append("{}{}".format(" " * tab_size, new_text))
        tmp.extend(lines[class_line:])
        content = ''.join(tmp)
    else:
        if comments:
            new_text += '\n'.join(comments) + "\n"
        content = content.replace(to_replace[0], new_text)
        content = content if not headers else ''.join(headers) + content

    remove(conanfile_path)
    save(conanfile_path, content)
Beispiel #52
0
    def info_build_test(self):
        """Test that the output of 'conan info --build' is correct

                    +-----------+
           +------> |  H0       | <--------+
           |        +------+----+          |
   private |               ^               |private
           |               |               |
      +----+-----+    +----+------+   +----+------+
      |  H1a     |    | H1b       |   | H1c       |
      +----+-----+    +-----------+   +----+------+
           ^                               ^
           |                               |
           |                               |
+----------+-+                     +-------+------+
|  H2a       | <------+    +-----> |   H2c        |
+------------+        |    |       +--------------+
                      |    |
                  +---+----+---+
                  |  H3        |
                  +------------+

        """

        self._export("H0", "0.1")

        self._export("H1a", "0.1", deps=[("H0/0.1@lu/st", "private")])
        self._export("H1b", "0.1", deps=["H0/0.1@lu/st"])
        self._export("H1c", "0.1", deps=[("H0/0.1@lu/st", "private")])

        self._export("H2a", "0.1", deps=["H1a/0.1@lu/st"])
        self._export("H2c", "0.1", deps=["H1c/0.1@lu/st"])

        self._export("H3", "0.1", deps=["H2a/0.1@lu/st", "H2c/0.1@lu/st"])

        # If we install H3 we need to build all except H1b
        self.clients["H3"].run("info . --build missing")
        self.assert_last_line(
            self.clients["H3"],
            "H0/0.1@lu/st, H1a/0.1@lu/st, H1c/0.1@lu/st, H2a/0.1@lu/st, H2c/0.1@lu/st"
        )

        # If we install H0 we need to build nothing (current project)
        self.clients["H0"].run("info ./conanfile.py --build missing")
        self.assert_last_line(self.clients["H0"], "")

        # If we install H0 we need to build H0
        self.clients["H1a"].run("info conanfile.py --build missing")
        self.assert_last_line(self.clients["H1a"], "H0/0.1@lu/st")

        # If we build and upload H1a and H1c, no more H0 (private) is required
        self.clients["H3"].run("install H1a/0.1@lu/st --build ")
        self.clients["H3"].run("install H1c/0.1@lu/st --build ")
        self.clients["H3"].run("upload H1a/0.1@lu/st --all")
        self.clients["H3"].run("upload H1c/0.1@lu/st --all")

        self.clients["H3"].run("remove '*' -f")
        self.clients["H3"].run("info . --build missing")
        self.assert_last_line(self.clients["H3"],
                              "H2a/0.1@lu/st, H2c/0.1@lu/st")

        # But if we force to build all, all nodes have to be built
        self.clients["H3"].run("remove '*' -f")
        self.clients["H3"].run("info ./conanfile.py --build")
        self.assert_last_line(
            self.clients["H3"],
            "H0/0.1@lu/st, H1a/0.1@lu/st, H1c/0.1@lu/st, H2a/0.1@lu/st, H2c/0.1@lu/st"
        )

        # Now upgrade the recipe H1a and upload it (but not the package)
        # so the package become outdated
        conanfile_path = os.path.join(self.clients["H1a"].current_folder,
                                      CONANFILE)
        conanfile = load(conanfile_path)
        conanfile += "\n# MODIFIED"
        save(conanfile_path, conanfile)
        self.clients["H1a"].run("export . lu/st")
        self.clients["H1a"].run("upload H1a/0.1@lu/st")  # NOW IS OUTDATED!

        # Without build outdated the built packages are the same
        self.clients["H3"].run("remove '*' -f")
        self.clients["H3"].run("info conanfile.py --build missing")
        self.assert_last_line(self.clients["H3"],
                              "H2a/0.1@lu/st, H2c/0.1@lu/st")

        # But with build outdated we have to build the private H0 (but only once) and H1a
        self.clients["H3"].run("remove '*' -f")
        self.clients["H3"].run("info . --build outdated")
        self.assert_last_line(
            self.clients["H3"],
            "H0/0.1@lu/st, H1a/0.1@lu/st, H2a/0.1@lu/st, H2c/0.1@lu/st")
    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)
Beispiel #54
0
    def upload_json_test(self):
        conanfile = """
from conans import ConanFile

class TestConan(ConanFile):
    name = "test"
    version = "0.1"

    def package(self):
        self.copy("mylib.so", dst="lib")
"""

        client = self._get_client()
        client.save({"conanfile.py": conanfile,
                     "mylib.so": ""})
        client.run("create . danimtb/testing")

        # Test conflict parameter error
        error = client.run("upload test/0.1@danimtb/* --all -p ewvfw --json upload.json",
                           ignore_error=True)
        self.assertTrue(error)
        json_path = os.path.join(client.current_folder, "upload.json")
        self.assertTrue(os.path.exists(json_path))
        json_content = load(json_path)
        output = json.loads(json_content)
        self.assertTrue(output["error"])
        self.assertEqual(0, len(output["uploaded"]))

        # Test invalid reference error
        error = client.run("upload fake/0.1@danimtb/testing --all --json upload.json",
                           ignore_error=True)
        self.assertTrue(error)
        json_path = os.path.join(client.current_folder, "upload.json")
        self.assertTrue(os.path.exists(json_path))
        json_content = load(json_path)
        output = json.loads(json_content)
        self.assertTrue(output["error"])
        self.assertEqual(0, len(output["uploaded"]))

        # Test normal upload
        client.run("upload test/0.1@danimtb/testing --all --json upload.json")
        self.assertTrue(os.path.exists(json_path))
        json_content = load(json_path)
        output = json.loads(json_content)
        output_expected = {"error": False,
                           "uploaded": [
                               {
                                   "recipe": {
                                       "id": "test/0.1@danimtb/testing",
                                       "remote_url": "unknown",
                                       "remote_name": "default",
                                       "time": "unknown"
                                   },
                                   "packages": [
                                       {
                                           "id": "5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9",
                                           "time": "unknown"
                                       }
                                   ]
                               }
                           ]}
        self.assertEqual(output_expected["error"], output["error"])
        self.assertEqual(len(output_expected["uploaded"]), len(output["uploaded"]))

        for i, item in enumerate(output["uploaded"]):
            self.assertEqual(output_expected["uploaded"][i]["recipe"]["id"], item["recipe"]["id"])
            self.assertEqual(output_expected["uploaded"][i]["recipe"]["remote_name"],
                             item["recipe"]["remote_name"])
            for j, subitem in enumerate(item["packages"]):
                self.assertEqual(output_expected["uploaded"][i]["packages"][j]["id"],
                                 subitem["id"])
Beispiel #55
0
    def test_basic(self, short_paths):
        client = TestClient()
        conanfile = """
from conans import ConanFile
class TestConan(ConanFile):
    name = "Hello"
    version = "0.1"
    settings = "os"

    def package(self):
        self.copy("*")
"""
        if short_paths:
            conanfile += "    short_paths = True"
        client.save({CONANFILE: conanfile})
        client.run("export . lasote/stable")
        client.save({"include/header.h": "//Windows header"})
        client.run("export-pkg . Hello/0.1@lasote/stable -s os=Windows")
        ref = ConanFileReference.loads("Hello/0.1@lasote/stable")
        win_pref = PackageReference(
            ref, "3475bd55b91ae904ac96fde0f106a136ab951a5e")
        package_folder = client.cache.package_layout(
            win_pref.ref, short_paths=short_paths).package(win_pref)
        if short_paths and platform.system() == "Windows":
            self.assertEqual(
                load(
                    os.path.join(
                        client.cache.package_layout(win_pref.ref,
                                                    False).package(win_pref),
                        ".conan_link")), package_folder)
        else:
            self.assertEqual(
                client.cache.package_layout(win_pref.ref).package(win_pref),
                package_folder)
        self.assertEqual(
            load(os.path.join(package_folder, "include/header.h")),
            "//Windows header")
        self._consume(client, ". -s os=Windows")
        self.assertIn(
            "Hello/0.1@lasote/stable:3475bd55b91ae904ac96fde0f106a136ab951a5e",
            client.out)

        # Now repeat
        client.save(
            {
                CONANFILE: conanfile,
                "include/header.h": "//Windows header2"
            },
            clean_first=True)
        # Without force it fails
        err = client.run("export-pkg . Hello/0.1@lasote/stable -s os=Windows",
                         assert_error=True)
        self.assertIn(
            "Package already exists. Please use --force, -f to overwrite it",
            client.out)
        self.assertTrue(err)
        # With force works
        client.run("export-pkg . Hello/0.1@lasote/stable -s os=Windows -f")
        self.assertEqual(
            load(os.path.join(package_folder, "include/header.h")),
            "//Windows header2")

        # Now use --install-folder
        client.save(
            {
                CONANFILE: conanfile,
                "include/header.h": "//Windows header3"
            },
            clean_first=True)
        # Without force it fails
        client.run("install . --install-folder=inst -s os=Windows")
        err = client.run("export-pkg . Hello/0.1@lasote/stable -if inst",
                         assert_error=True)
        self.assertTrue(err)
        self.assertIn(
            "Package already exists. Please use --force, -f to overwrite it",
            client.out)
        # With force works
        client.run("export-pkg . Hello/0.1@lasote/stable -if inst -f")
        self.assertIn(
            "Hello/0.1@lasote/stable: Package '3475bd55b91ae904ac96fde0f106a136ab951a5e'"
            " created", client.out)
        self.assertEqual(
            load(os.path.join(package_folder, "include/header.h")),
            "//Windows header3")

        # we can specify settings too
        client.save({"include/header.h": "//Windows header4"})
        client.run(
            "export-pkg . Hello/0.1@lasote/stable -if inst -f -s os=Windows")
        self.assertIn(
            "Hello/0.1@lasote/stable: Package '3475bd55b91ae904ac96fde0f106a136ab951a5e'"
            " created", client.out)
        self.assertEqual(
            load(os.path.join(package_folder, "include/header.h")),
            "//Windows header4")

        # Try to specify a install folder with no files
        client.run("export-pkg . Hello/0.1@lasote/stable -if fake",
                   assert_error=True)
        self.assertIn("ERROR: Failed to load graphinfo file in install-folder",
                      client.out)
Beispiel #56
0
    def private_order_test(self):
        # https://github.com/conan-io/conan/issues/3006
        client = TestClient()
        conanfile = """from conans import ConanFile
class LibBConan(ConanFile):
    def package_info(self):
        self.cpp_info.libs = ["LibC"]
"""
        client.save({"conanfile.py": conanfile})
        client.run("create . LibC/0.1@user/channel")

        conanfile = """from conans import ConanFile
class LibCConan(ConanFile):
    requires = "LibC/0.1@user/channel"
    def package_info(self):
        self.cpp_info.libs = ["LibB"]
"""
        client.save({"conanfile.py": conanfile})
        client.run("create . LibB/0.1@user/channel")

        conanfile = """from conans import ConanFile
class LibCConan(ConanFile):
    requires = ("LibB/0.1@user/channel", "private"), "LibC/0.1@user/channel"
"""
        client.save({"conanfile.py": conanfile})
        client.run("install . -g cmake")
        conanbuildinfo = load(
            os.path.join(client.current_folder, "conanbuildinfo.cmake"))
        self.assertIn("set(CONAN_LIBS LibB LibC ${CONAN_LIBS})",
                      conanbuildinfo)
        # Change private
        conanfile = """from conans import ConanFile
class LibCConan(ConanFile):
    requires = "LibB/0.1@user/channel", ("LibC/0.1@user/channel", "private")
"""
        client.save({"conanfile.py": conanfile})
        client.run("install . -g cmake")
        conanbuildinfo = load(
            os.path.join(client.current_folder, "conanbuildinfo.cmake"))
        self.assertIn("set(CONAN_LIBS LibB LibC ${CONAN_LIBS})",
                      conanbuildinfo)
        # Change order
        conanfile = """from conans import ConanFile
class LibCConan(ConanFile):
    requires = ("LibC/0.1@user/channel", "private"), "LibB/0.1@user/channel"
"""
        client.save({"conanfile.py": conanfile})
        client.run("install . -g cmake")
        conanbuildinfo = load(
            os.path.join(client.current_folder, "conanbuildinfo.cmake"))
        self.assertIn("set(CONAN_LIBS LibB LibC ${CONAN_LIBS})",
                      conanbuildinfo)
        # Change order
        conanfile = """from conans import ConanFile
class LibCConan(ConanFile):
    requires = "LibC/0.1@user/channel", ("LibB/0.1@user/channel", "private")
"""
        client.save({"conanfile.py": conanfile})
        client.run("install . -g cmake")
        conanbuildinfo = load(
            os.path.join(client.current_folder, "conanbuildinfo.cmake"))
        self.assertIn("set(CONAN_LIBS LibB LibC ${CONAN_LIBS})",
                      conanbuildinfo)
Beispiel #57
0
    def build_requires_test(self):
        # https://github.com/conan-io/conan/issues/3075
        client = TestClient()
        tool = """from conans import ConanFile
class Tool(ConanFile):
    def package_info(self):
        self.cpp_info.libs = ["MyToolLib"]
"""
        client.save({"conanfile.py": tool})
        client.run("create . Tool/0.1@user/testing")

        conanfile = """from conans import ConanFile
import os
class Pkg(ConanFile):
    requires = {deps}
    build_requires = "Tool/0.1@user/testing"
    generators = "cmake"
"""

        def files(name, depend=None):
            deps = ('"Hello%s/0.1@lasote/stable"' %
                    depend) if depend else "None"
            return {"conanfile.py": conanfile.format(deps=deps, name=name)}

        client.save(files("C"), path=os.path.join(client.current_folder, "C"))
        client.save(files("B", "C"),
                    path=os.path.join(client.current_folder, "B"))
        client.save(files("A", "B"),
                    path=os.path.join(client.current_folder, "A"))

        project = dedent("""
            editables:
                HelloB/0.1@lasote/stable:
                    path: B
                HelloC/0.1@lasote/stable:
                    path: C
                HelloA/0.1@lasote/stable:
                    path: A
            layout: layout
            root: HelloA/0.1@lasote/stable
            """)
        layout = dedent("""
            [build_folder]
            build
            """)
        client.save({"conanws.yml": project, "layout": layout})

        client.run("workspace install conanws.yml")
        self.assertIn(
            "HelloC/0.1@lasote/stable: Applying build-requirement: Tool/0.1@user/testing",
            client.out)
        self.assertIn(
            "HelloB/0.1@lasote/stable: Applying build-requirement: Tool/0.1@user/testing",
            client.out)
        self.assertIn(
            "HelloA/0.1@lasote/stable: Applying build-requirement: Tool/0.1@user/testing",
            client.out)
        for sub in ("A", "B", "C"):
            conanbuildinfo = load(
                os.path.join(client.current_folder, sub, "build",
                             "conanbuildinfo.cmake"))
            self.assertIn("set(CONAN_LIBS_TOOL MyToolLib)", conanbuildinfo)
Beispiel #58
0
    def conan_scopes_test(self):
        client = TestClient()
        conanfile = '''
from conans import ConanFile

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"
    def build(self):
        if self.scope.dev:
            self.output.warn("DEP DEV")
        if self.scope.other:
            self.output.warn("DEP OTHER")
        '''
        files = {}
        files["conanfile.py"] = conanfile
        client.save(files)
        client.run("export lasote/stable")
        conanfile = '''
from conans import ConanFile

class HelloConan(ConanFile):
    requires = "Hello/0.1@lasote/stable"
    def config(self):
        self.output.info(self.scope)
        if self.scope.dev:
            self.output.warn("CONFIG_CONSUMER DEV")
        if self.scope.other:
            self.output.warn("CONFIG_CONSUMER OTHER")
    def build(self):
        if self.scope.dev:
            self.output.warn("BUILD_CONSUMER DEV")
        if self.scope.other:
            self.output.warn("BUILD_CONSUMER OTHER")
        '''
        files["conanfile.py"] = conanfile
        client.save(files, clean_first=True)

        client.run("install --build")

        self.assertNotIn("WARN: DEP DEV", client.user_io.out)
        self.assertNotIn("WARN: DEP OTHER", client.user_io.out)
        self.assertIn("WARN: CONFIG_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: CONFIG_CONSUMER OTHER", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER OTHER", client.user_io.out)

        client.run("install --build -sc other=True")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("[scope]    dev=True    other=True",
                      "".join(conaninfo.splitlines()))
        self.assertIn("dev=True, other=True", client.user_io.out)
        self.assertNotIn("WARN: DEP DEV", client.user_io.out)
        self.assertNotIn("WARN: DEP OTHER", client.user_io.out)
        self.assertIn("WARN: CONFIG_CONSUMER DEV", client.user_io.out)
        self.assertIn("WARN: CONFIG_CONSUMER OTHER", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER OTHER", client.user_io.out)

        client.run("install --build -sc Hello:dev=True")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("[scope]    dev=True    Hello:dev=True",
                      "".join(conaninfo.splitlines()))
        self.assertIn("WARN: DEP DEV", client.user_io.out)
        self.assertNotIn("WARN: DEP OTHER", client.user_io.out)
        self.assertIn("WARN: CONFIG_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: CONFIG_CONSUMER OTHER", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER OTHER", client.user_io.out)

        client.run("install --build -sc Hello:other=True")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("[scope]    dev=True    Hello:other=True",
                      "".join(conaninfo.splitlines()))
        self.assertNotIn("WARN: DEP DEV", client.user_io.out)
        self.assertIn("WARN: DEP OTHER", client.user_io.out)
        self.assertIn("WARN: CONFIG_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: CONFIG_CONSUMER OTHER", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER OTHER", client.user_io.out)

        client.run("install --build -sc Hello:other=False")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("[scope]    dev=True    Hello:other=False",
                      "".join(conaninfo.splitlines()))
        self.assertNotIn("WARN: DEP DEV", client.user_io.out)
        self.assertNotIn("WARN: DEP OTHER", client.user_io.out)
        self.assertIn("WARN: CONFIG_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: CONFIG_CONSUMER OTHER", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER OTHER", client.user_io.out)

        client.run("build .")
        conaninfo = load(os.path.join(client.current_folder, "conaninfo.txt"))
        self.assertIn("[scope]    dev=True    Hello:other=False",
                      "".join(conaninfo.splitlines()))
        self.assertNotIn("WARN: DEP DEV", client.user_io.out)
        self.assertNotIn("WARN: DEP OTHER", client.user_io.out)
        self.assertNotIn("WARN: CONFIG_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: CONFIG_CONSUMER OTHER", client.user_io.out)
        self.assertIn("WARN: BUILD_CONSUMER DEV", client.user_io.out)
        self.assertNotIn("WARN: BUILD_CONSUMER OTHER", client.user_io.out)
Beispiel #59
0
    def test_download_retries(self):
        http_server = StoppableThreadBottle()

        with tools.chdir(tools.mkdir_tmp()):
            with open("manual.html", "w") as fmanual:
                fmanual.write("this is some content")
                manual_file = os.path.abspath("manual.html")

        from bottle import auth_basic

        @http_server.server.get("/manual.html")
        def get_manual():
            return static_file(os.path.basename(manual_file),
                               os.path.dirname(manual_file))

        def check_auth(user, password):
            # Check user/password here
            return user == "user" and password == "passwd"

        @http_server.server.get('/basic-auth/<user>/<password>')
        @auth_basic(check_auth)
        def get_manual_auth(user, password):
            return static_file(os.path.basename(manual_file),
                               os.path.dirname(manual_file))

        http_server.run_server()

        out = TestBufferConanOutput()

        dest = os.path.join(temp_folder(), "manual.html")
        tools.download("http://localhost:%s/manual.html" % http_server.port,
                       dest,
                       out=out,
                       retry=3,
                       retry_wait=0,
                       requester=requests)
        self.assertTrue(os.path.exists(dest))
        content = load(dest)

        # overwrite = False
        with self.assertRaises(ConanException):
            tools.download("http://localhost:%s/manual.html" %
                           http_server.port,
                           dest,
                           out=out,
                           retry=2,
                           retry_wait=0,
                           overwrite=False,
                           requester=requests)

        # overwrite = True
        tools.download("http://localhost:%s/manual.html" % http_server.port,
                       dest,
                       out=out,
                       retry=2,
                       retry_wait=0,
                       overwrite=True,
                       requester=requests)
        self.assertTrue(os.path.exists(dest))
        content_new = load(dest)
        self.assertEqual(content, content_new)

        # Not authorized
        with self.assertRaises(ConanException):
            tools.download("http://localhost:%s/basic-auth/user/passwd" %
                           http_server.port,
                           dest,
                           overwrite=True,
                           requester=requests,
                           out=out,
                           retry=0,
                           retry_wait=0)

        # Authorized
        tools.download("http://localhost:%s/basic-auth/user/passwd" %
                       http_server.port,
                       dest,
                       auth=("user", "passwd"),
                       overwrite=True,
                       requester=requests,
                       out=out,
                       retry=0,
                       retry_wait=0)

        # Authorized using headers
        tools.download("http://localhost:%s/basic-auth/user/passwd" %
                       http_server.port,
                       dest,
                       headers={"Authorization": "Basic dXNlcjpwYXNzd2Q="},
                       overwrite=True,
                       requester=requests,
                       out=out,
                       retry=0,
                       retry_wait=0)
        http_server.stop()
    def test_check_conaninfo_completion(self):
        """
        consumer -> B -> C
                      -> D (conditional)

        The overwritten environment variables caused by the consumer have to be reflected in B's conaninfo.txt
        """
        client = TestClient()
        conanfile = """
from conans import ConanFile
class LibConan(ConanFile):
    name = "libC"
    version = "1.0"

    def package_info(self):
        self.env_info.MYVAR = "ValueByLibC"
"""
        client.save({"conanfile.py": conanfile})
        client.run("export . foo/bar")

        conanfile = """
from conans import ConanFile
class LibConan(ConanFile):
    name = "libD"
    version = "1.0"

    def package_info(self):
        self.env_info.MYVAR = "ValueByLibD"
"""
        client.save({"conanfile.py": conanfile})
        client.run("export . foo/bar")

        conanfile = """
import os
from conans import ConanFile
class LibConan(ConanFile):
    name = "libB"
    version = "1.0"

    def requirements(self):
        if os.environ.get("DEP", None) == "C":
            self.requires.add("libC/1.0@foo/bar")
        else:
            self.requires.add("libD/1.0@foo/bar")

    def build_info(self):
        self.output.warn("Value of MYVAR: %s" % os.environ["MYVAR"])
"""
        client.save({"conanfile.py": conanfile})
        client.run("export . foo/bar")

        pref = PackageReference.loads(
            "libB/1.0@foo/bar:5fecb9aaf431791c8c06ab146f3451823f982bb8")

        # With no overrides, B takes dependency D and the value should be ValueByLibD
        client.run("install libB/1.0@foo/bar --build")
        self.assertTrue("Value of MYVAR: ValueByLibD")
        conaninfo = load(
            os.path.join(
                client.cache.package_layout(pref.ref).package(pref),
                CONANINFO))
        self.assertTrue(conaninfo.endswith("[env]\n\n"))  # Not user input env

        # B takes dependency C and the value should be ValueByLibC
        client.run("install libB/1.0@foo/bar --build -e DEP=C")
        self.assertTrue("Value of MYVAR: ValueByLibC")
        conaninfo = load(
            os.path.join(
                client.cache.package_layout(pref.ref).package(pref),
                CONANINFO))
        self.assertTrue(conaninfo.endswith("[env]\n\n"))  # Not user input env

        # Consumer overrides MYVAR, so his conaninfo should have it
        client.run("install libB/1.0@foo/bar --build -e MYVAR=ValueByConsumer")
        self.assertTrue("Value of MYVAR: ValueByConsumer")
        conaninfo = load(
            os.path.join(
                client.cache.package_layout(pref.ref).package(pref),
                CONANINFO))
        self.assertTrue(
            conaninfo.endswith("[env]\n    MYVAR=ValueByConsumer\n"))

        # Consumer overrides MYVAR, so his conaninfo should have it, but not the libC, because
        # is not a dependency
        client.run(
            "install libB/1.0@foo/bar --build -e libB:MYVAR=ValueByConsumer "
            "-e libC:MYVAR=OtherValue")
        self.assertTrue("Value of MYVAR: ValueByConsumer")
        conaninfo = load(
            os.path.join(
                client.cache.package_layout(pref.ref).package(pref),
                CONANINFO))
        self.assertTrue(
            conaninfo.endswith("[env]\n    libB:MYVAR=ValueByConsumer\n"))

        # Consumer overrides MYVAR, so his conaninfo should have it, both libB and libD
        client.run(
            "install libB/1.0@foo/bar --build -e libB:MYVAR=ValueByConsumer "
            "-e libD:MYVAR=OtherValue")
        self.assertTrue("Value of MYVAR: ValueByConsumer")
        conaninfo = load(
            os.path.join(
                client.cache.package_layout(pref.ref).package(pref),
                CONANINFO))
        self.assertTrue(
            conaninfo.endswith(
                "[env]\n    libB:MYVAR=ValueByConsumer\n"
                "    libD:MYVAR=OtherValue\n"))  # Not user input env