def test_profile_test_requires(self):
        client = TestClient()
        self._create(client)

        test_conanfile = """
import os
from conans import ConanFile, tools

class TestMyLib(ConanFile):
    requires = "MyLib/0.1@lasote/stable"

    def build(self):
        self.run("mytool")
        with tools.pythonpath(self):
            import mypythontool
            self.output.info(mypythontool.tool_hello_world())
    def test(self):
        pass
        """
        client.save({CONANFILE: lib_conanfile,
                     "test_package/conanfile.py": test_conanfile,
                     "profile.txt": profile,
                     "profile2.txt": profile2}, clean_first=True)

        client.run("test_package --profile ./profile.txt --build missing")
        self.assertEqual(2, str(client.user_io.out).splitlines().count("Hello World!"))
        self.assertIn("MyLib/0.1@lasote/stable: Hello world from python tool!", client.user_io.out)
        self.assertIn("Project: Hello world from python tool!", client.user_io.out)
示例#2
0
文件: user_test.py 项目: nesono/conan
 def test_command_user(self):
     """ Test that the user can be shown and changed, and it is reflected in the
     user cache localdb
     """
     client = TestClient()
     client.run('user')
     self.assertIn("ERROR: No remotes defined", client.user_io.out)
示例#3
0
    def conditional_requirements_test(self):
        conanfile = """from conans import ConanFile

class TestConanLib(ConanFile):
    name = "Hello"
    version = "0.1"
    settings = "os", "build_type", "product"
        """
        test_conanfile = '''
from conans import ConanFile

class TestConanLib(ConanFile):
    requires = "Hello/0.1@lasote/testing"
    settings = "os", "build_type", "product"
    def requirements(self):
        self.output.info("Conditional test requirement: %s, %s, %s"
                         % (self.settings.os, self.settings.build_type, self.settings.product))

    def test(self):
        pass
'''
        client = TestClient()
        settings_path = client.client_cache.settings_path
        client.client_cache.settings
        settings = load(settings_path)
        settings += "\nproduct: [onion, potato]"
        save(settings_path, settings)
        client.save({"conanfile.py": conanfile,
                     "test_package/conanfile.py": test_conanfile})
        client.run("create . lasote/testing -s os=Windows -s product=onion -s build_type=Release")
        self.assertIn("PROJECT: Conditional test requirement: Windows, Release, onion",
                      client.user_io.out)
示例#4
0
class InstallCWDTest(unittest.TestCase):

    def setUp(self):
        self.client = TestClient(users={"myremote": [("lasote", "mypass")]})
        conanfile = """
import os
from conans import ConanFile, tools, CMake

class MyLib(ConanFile):
    name = "MyLib"
    version = "0.1"
    exports = "*"
    settings = "os", "compiler", "arch", "build_type"
    generators = "cmake"

    def build(self):
        pass
"""
        self.client.save({CONANFILE: conanfile})
        self.client.run("export . lasote/stable")

    def test_install_cwd(self):
        self.client.save({CONANFILE_TXT: "[requires]MyLib/0.1@lasote/stable"}, clean_first=True)
        os.mkdir(os.path.join(self.client.current_folder, "new"))
        self.client.run("install . --install-folder new -g cmake")
        self.assertTrue(os.path.join(self.client.current_folder, "new", "conanbuildinfo.cmake"))

    def install_ref(self):
        self.client.run("install MyLib/0.1@lasote/stable --build=missing")
        self.assertEqual(["conanfile.py"], os.listdir(self.client.current_folder))
示例#5
0
    def package_files_test(self):
        if platform.system() == "Windows":
            return

        client = TestClient()
        conanfile = """
from conans import ConanFile
class TestConan(ConanFile):
    name = "Hello"
    version = "0.1"

    def package(self):
        self.copy("*", symlinks=True)
    """
        client.save({"recipe/conanfile.py": conanfile})
        file1 = os.path.join(client.current_folder, "file1.txt")
        file2 = os.path.join(client.current_folder, "version1/file2.txt")
        file11 = os.path.join(client.current_folder, "file1.txt.1")
        latest = os.path.join(client.current_folder, "latest")
        save(file1, "Hello1")
        os.symlink("file1.txt", file11)
        save(file2, "Hello2")
        os.symlink("version1", latest)
        client.run("export-pkg ./recipe Hello/0.1@lasote/stable")
        ref = PackageReference.loads("Hello/0.1@lasote/stable:"
                                     "5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")

        self._check(client, ref, build=False)
示例#6
0
class ProfilesEnvironmentTest(unittest.TestCase):

    def setUp(self):
        self.client = TestClient()

    def build_with_profile_test(self):
        self._create_profile("scopes_env", {},
                             {},  # undefined scope do not apply to my packages
                             {"CXX": "/path/tomy/g++_build", "CC": "/path/tomy/gcc_build"})

        self.client.save({CONANFILE: conanfile_dep})
        self.client.run("export lasote/testing")

        self.client.save({CONANFILE: conanfile_scope_env}, clean_first=True)
        self.client.run("install --build=missing --pr scopes_env")
        self.client.run("build")
        self.assertRegexpMatches(str(self.client.user_io.out), "PATH=['\"]*/path/to/my/folder")
        self._assert_env_variable_printed("CC", "/path/tomy/gcc_build")
        self._assert_env_variable_printed("CXX", "/path/tomy/g++_build")

    def _assert_env_variable_printed(self, name, value):
        self.assertIn("%s=%s" % (name, value), self.client.user_io.out)

    def _create_profile(self, name, settings, scopes=None, env=None):
        env = env or {}
        profile = Profile()
        profile._settings = settings or {}
        if scopes:
            profile.scopes = Scopes.from_list(["%s=%s" % (key, value) for key, value in scopes.items()])
        for varname, value in env.items():
            profile.env_values.add(varname, value)
        save(os.path.join(self.client.client_cache.profiles_path, name), profile.dumps())
示例#7
0
 def base_profile_generated_test(self):
     """we are testing that the default profile is created (when not existing, fresh install)
      even when you run a create with a profile"""
     client = TestClient()
     client.save({CONANFILE: conanfile_scope_env,
                       "myprofile": "include(default)\n[settings]\nbuild_type=Debug"})
     client.run("create . conan/testing --profile myprofile")
示例#8
0
    def test_rel_path(self):
        base_folder = temp_folder()
        source_folder = os.path.join(base_folder, "source")
        current_folder = os.path.join(base_folder, "current")
        os.makedirs(current_folder)
        client = TestClient(current_folder=current_folder)
        files = cpp_hello_conan_files("Hello0", "0.1")
        conan_ref = ConanFileReference("Hello0", "0.1", "lasote", "stable")
        client.save(files, path=source_folder)
        client.run("export lasote/stable --path=../source")
        reg_path = client.paths.export(conan_ref)
        manif = FileTreeManifest.loads(load(client.paths.digestfile_conanfile(conan_ref)))

        self.assertIn('%s: A new conanfile.py version was exported' % str(conan_ref),
                      client.user_io.out)
        self.assertIn('%s: Folder: %s' % (str(conan_ref), reg_path), client.user_io.out)
        self.assertTrue(os.path.exists(reg_path))

        for name in list(files.keys()):
            self.assertTrue(os.path.exists(os.path.join(reg_path, name)))

        expected_sums = {'hello.cpp': '4f005274b2fdb25e6113b69774dac184',
                         'main.cpp': '0479f3c223c9a656a718f3148e044124',
                         'CMakeLists.txt': '52546396c42f16be3daf72ecf7ab7143',
                         'conanfile.py': '355949fbf0b4fc32b8f1c5a338dfe1ae',
                         'executable': '68b329da9893e34099c7d8ad5cb9c940',
                         'helloHello0.h': '9448df034392fc8781a47dd03ae71bdd'}
        self.assertEqual(expected_sums, manif.file_sums)
示例#9
0
class ConflictDiamondTest(unittest.TestCase):

    def setUp(self):
        self.client = TestClient()

    def _export(self, name, version, deps=None, export=True):
        deps = ", ".join(['"%s"' % d for d in deps or []]) or '""'
        conanfile = """
from conans import ConanFile, CMake
import os

class HelloReuseConan(ConanFile):
    name = "%s"
    version = "%s"
    requires = %s
""" % (name, version, deps)
        files = {CONANFILE: conanfile}
        self.client.save(files, clean_first=True)
        if export:
            self.client.run("export . lasote/stable")

    def reuse_test(self):
        self._export("Hello0", "0.1")
        self._export("Hello0", "0.2")
        self._export("Hello1", "0.1", ["Hello0/0.1@lasote/stable"])
        self._export("Hello2", "0.1", ["Hello0/0.2@lasote/stable"])
        self._export("Hello3", "0.1", ["Hello1/0.1@lasote/stable", "Hello2/0.1@lasote/stable"],
                     export=False)

        error = self.client.run("install . --build missing", ignore_error=True)
        self.assertTrue(error)
        self.assertIn("Conflict in Hello2/0.1@lasote/stable", self.client.user_io.out)
        self.assertNotIn("PROJECT: Generated conaninfo.txt", self.client.user_io.out)
示例#10
0
 def test_disable_linter(self):
     client = TestClient()
     client.save({CONANFILE: conanfile})
     with tools.environment_append({"CONAN_RECIPE_LINTER": "False"}):
         client.run("export . lasote/stable")
         self.assertNotIn("ERROR: Py3 incompatibility", client.user_io.out)
         self.assertNotIn("WARN: Linter", client.user_io.out)
示例#11
0
    def upload_test(self):
        conan_reference = ConanFileReference.loads("Hello0/0.1@lasote/stable")
        files = cpp_hello_conan_files("Hello0", "0.1", build=False)
        self.client.save(files)
        self.client.run("export . lasote/stable")
        self.client.run("upload %s" % str(conan_reference))

        self.client.run("info %s" % str(conan_reference))
        self.assertIn("remote0=http://", self.client.user_io.out)

        # The remote, once fixed does not change
        self.client.run("upload %s -r=remote1" % str(conan_reference))
        self.client.run("info %s" % str(conan_reference))
        self.assertIn("remote0=http://", self.client.user_io.out)

        # Now install it in other machine from remote 0
        client2 = TestClient(servers=self.servers, users=self.users)
        client2.run("install %s --build=missing" % str(conan_reference))
        client2.run("info %s" % str(conan_reference))
        self.assertIn("remote0=http://", client2.user_io.out)

        # Now install it in other machine from remote 1
        servers = self.servers.copy()
        servers.pop("remote0")
        client3 = TestClient(servers=servers, users=self.users)
        client3.run("install %s --build=missing" % str(conan_reference))
        client3.run("info %s" % str(conan_reference))
        self.assertIn("remote1=http://", client3.user_io.out)
示例#12
0
文件: new_test.py 项目: nesono/conan
    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)
示例#13
0
    def test_patch_new_delete(self):
        conanfile = base_conanfile + '''
    def build(self):
        from conans.tools import load, save
        save("oldfile", "legacy code")
        assert(os.path.exists("oldfile"))
        patch_content = """--- /dev/null
+++ b/newfile
@@ -0,0 +0,3 @@
+New file!
+New file!
+New file!
--- a/oldfile
+++ b/dev/null
@@ -0,1 +0,0 @@
-legacy code
"""
        patch(patch_string=patch_content)
        self.output.info("NEW FILE=%s" % load("newfile"))
        self.output.info("OLD FILE=%s" % os.path.exists("oldfile"))
'''
        client = TestClient()
        client.save({"conanfile.py": conanfile})
        client.run("create . user/testing")
        self.assertIn("test/1.9.10@user/testing: NEW FILE=New file!\nNew file!\nNew file!\n",
                      client.out)
        self.assertIn("test/1.9.10@user/testing: OLD FILE=False", client.out)
示例#14
0
    def test_package_env_test(self):
        client = TestClient()
        conanfile = '''
from conans import ConanFile

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"
    def package_info(self):
        self.env_info.PYTHONPATH.append("new/pythonpath/value")
        '''
        test_package = '''
import os
from conans import ConanFile

class HelloTestConan(ConanFile):
    requires = "Hello/0.1@lasote/testing"

    def build(self):
        assert("new/pythonpath/value" in os.environ["PYTHONPATH"])

    def test(self):
        assert("new/pythonpath/value" in os.environ["PYTHONPATH"])
'''

        client.save({"conanfile.py": conanfile, "test_package/conanfile.py": test_package})
        client.run("test_package")
示例#15
0
    def scopes_test_package_test(self):
        client = TestClient()
        conanfile = """
from conans import ConanFile

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

    def build(self):
        self.output.info("Scope: %s" % self.scope)
"""
        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,
                     "test/conanfile.py": test_conanfile})
        client.run("test_package --scope Hello:dev=True --build=missing")
        self.assertIn("Hello/0.1@lasote/stable: Scope: dev=True", client.user_io.out)
示例#16
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)
示例#17
0
 def verbose_version_test(self):
     client = TestClient()
     conanfile = TestConanFile("MyPkg", "0.1", requires=["MyOtherPkg/[~0.1]@user/testing"])
     client.save({CONANFILE: str(conanfile)})
     error = client.run("install . --build", ignore_error=True)
     self.assertTrue(error)
     self.assertIn("from requirement 'MyOtherPkg/[~0.1]@user/testing'", client.user_io.out)
示例#18
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")
示例#19
0
    def test_export_a_new_version(self):
        self._create_packages_and_builds()
        # Export an update of the same conans

        conan2 = TestClient(self.conan.base_folder)
        files2 = cpp_hello_conan_files("Hello0", "0.1")
        files2[CONANFILE] = "# insert comment\n %s" % files2[CONANFILE]
        conan2.save(files2)
        conan2.run("export lasote/stable")

        reg_path3 = conan2.paths.export(self.conan_ref)
        digest3 = FileTreeManifest.loads(load(conan2.paths.digestfile_conanfile(self.conan_ref)))

        self.assertIn('%s: A new conanfile.py version was exported' % str(self.conan_ref),
                      self.conan.user_io.out)
        self.assertIn('%s: Folder: %s' % (str(self.conan_ref), reg_path3), self.conan.user_io.out)

        self.assertTrue(os.path.exists(reg_path3))

        for name in list(files2.keys()):
            self.assertTrue(os.path.exists(os.path.join(reg_path3, name)))

        expected_sums = {'hello.cpp': '4f005274b2fdb25e6113b69774dac184',
                         'main.cpp': '0479f3c223c9a656a718f3148e044124',
                         'CMakeLists.txt': '52546396c42f16be3daf72ecf7ab7143',
                         'conanfile.py': 'ad17cf00b3142728b03ac37782b9acd9',
                         'executable': '68b329da9893e34099c7d8ad5cb9c940',
                         'helloHello0.h': '9448df034392fc8781a47dd03ae71bdd'}
        self.assertEqual(expected_sums, digest3.file_sums)
示例#20
0
    def test_global_tools_overrided(self):
        client = TestClient()

        tools._global_requester = None
        tools._global_output = None

        conanfile = """
from conans import ConanFile, tools

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

    def build(self):
        assert(tools._global_requester != None)
        assert(tools._global_output != None)
        """
        client.save({"conanfile.py": conanfile})
        client.run("build")


        # Not test the real commmand get_command if it's setting the module global vars
        tools._global_requester = None
        tools._global_output = None
        tmp = tempfile.mkdtemp()
        conf = default_client_conf.replace("\n[proxies]", "\n[proxies]\nhttp = http://myproxy.com")
        os.mkdir(os.path.join(tmp, ".conan"))
        save(os.path.join(tmp, ".conan", CONAN_CONF), conf)
        with tools.environment_append({"CONAN_USER_HOME": tmp}):
            conan_api = ConanAPIV1.factory()
        conan_api.remote_list()
        self.assertEquals(tools._global_requester.proxies, {"http": "http://myproxy.com"})

        self.assertIsNotNone(tools._global_output.warn)
示例#21
0
    def test_export_the_same_code(self):
        file_list = self._create_packages_and_builds()
        # Export the same conans

        conan2 = TestClient(self.conan.base_folder)
        files2 = cpp_hello_conan_files("Hello0", "0.1")
        conan2.save(files2)
        conan2.run("export lasote/stable")
        reg_path2 = conan2.paths.export(self.conan_ref)
        digest2 = FileTreeManifest.loads(load(conan2.paths.digestfile_conanfile(self.conan_ref)))

        self.assertNotIn('A new Conan version was exported', conan2.user_io.out)
        self.assertNotIn('Cleaning the old builds ...', conan2.user_io.out)
        self.assertNotIn('Cleaning the old packs ...', conan2.user_io.out)
        self.assertNotIn('All the previous packs were cleaned', conan2.user_io.out)
        self.assertIn('%s: A new conanfile.py version was exported' % str(self.conan_ref),
                      self.conan.user_io.out)
        self.assertIn('%s: Folder: %s' % (str(self.conan_ref), reg_path2), self.conan.user_io.out)
        self.assertTrue(os.path.exists(reg_path2))

        for name in list(files2.keys()):
            self.assertTrue(os.path.exists(os.path.join(reg_path2, name)))

        expected_sums = {'hello.cpp': '4f005274b2fdb25e6113b69774dac184',
                         'main.cpp': '0479f3c223c9a656a718f3148e044124',
                         'CMakeLists.txt': '52546396c42f16be3daf72ecf7ab7143',
                         'conanfile.py': '355949fbf0b4fc32b8f1c5a338dfe1ae',
                         'executable': '68b329da9893e34099c7d8ad5cb9c940',
                         'helloHello0.h': '9448df034392fc8781a47dd03ae71bdd'}
        self.assertEqual(expected_sums, digest2.file_sums)

        for f in file_list:
            self.assertTrue(os.path.exists(f))
示例#22
0
 def _upload_with_credentials(credentials):
     cli = TestClient(servers=self.servers, users={})
     save(os.path.join(cli.current_folder, CONANFILE), conan_content)
     cli.run("export . lasote/testing")
     with tools.environment_append(credentials):
         cli.run("upload %s" % str(self.conan_reference))
     return cli
示例#23
0
 def test_with_no_user(self):
     test_server = TestServer()
     client = TestClient(servers={"default": test_server})
     error = client.run('user -p test', ignore_error=True)
     self.assertTrue(error)
     self.assertIn("ERROR: User for remote 'default' is not defined. [Remote: default]",
                   client.out)
示例#24
0
 def new_without_test(self):
     client = TestClient()
     client.run('new MyPackage/1.3@myuser/testing')
     root = client.current_folder
     self.assertTrue(os.path.exists(os.path.join(root, "conanfile.py")))
     self.assertFalse(os.path.exists(os.path.join(root, "test_package/conanfile.py")))
     self.assertFalse(os.path.exists(os.path.join(root, "test_package/CMakeLists.txt")))
     self.assertFalse(os.path.exists(os.path.join(root, "test_package/example.cpp")))
示例#25
0
 def verify_ssl_error_test(self):
     client = TestClient()
     error = client.run("remote add my-remote http://someurl some_invalid_option=foo",
                        ignore_error=True)
     self.assertTrue(error)
     self.assertIn("ERROR: Unrecognized boolean value 'some_invalid_option=foo'",
                   client.user_io.out)
     self.assertEqual("", load(client.client_cache.registry))
示例#26
0
 def invalid_reference_error_test(self):
     """ Trying to upload an invalid reference must raise an Error
     """
     client = TestClient()
     error = client.run("upload some_nonsense -p hash1", ignore_error=True)
     self.assertTrue(error)
     self.assertIn("ERROR: -p parameter only allowed with a valid recipe reference",
                   client.user_io.out)
示例#27
0
 def not_existing_error_test(self):
     """ Trying to upload with pattern not matched must raise an Error
     """
     client = TestClient()
     error = client.run("upload some_nonsense", ignore_error=True)
     self.assertTrue(error)
     self.assertIn("ERROR: No packages found matching pattern 'some_nonsense'",
                   client.user_io.out)
示例#28
0
    def create_empty_property_file_test(self):

        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")
        props_file = client.client_cache.put_headers_path
        self.assertTrue(os.path.exists(props_file))
示例#29
0
 def search_with_no_registry_test(self):
     # https://github.com/conan-io/conan/issues/2589
     client = TestClient()
     os.remove(os.path.join(client.client_cache.registry))
     error = client.run("search nonexist/1.0@lasote/stable -r=myremote", ignore_error=True)
     self.assertTrue(error)
     self.assertIn("WARN: Remotes registry file missing, creating default one", client.out)
     self.assertIn("ERROR: No remote 'myremote' defined in remotes", client.out)
示例#30
0
 def non_existing_package_error_test(self):
     """ Trying to upload a non-existing package must raise an Error
     """
     client = TestClient()
     error = client.run("upload Pkg/0.1@user/channel -p hash1", ignore_error=True)
     self.assertTrue(error)
     self.assertIn("ERROR: There is no local conanfile exported as Pkg/0.1@user/channel",
                   client.user_io.out)
示例#31
0
    def test_conan_data_everywhere(self):
        client = TestClient()
        conanfile = """from conans import ConanFile

class Lib(ConanFile):

    def _assert_data(self):
        assert(self.conan_data["sources"]["all"]["url"] == "the url")
        assert(self.conan_data["sources"]["all"]["other"] == "field")
        self.output.info("My URL: {}".format(self.conan_data["sources"]["all"]["url"]))

    def configure(self):
        self._assert_data()

    def config_options(self):
        self._assert_data()

    def source(self):
        self._assert_data()

    def build(self):
        self._assert_data()

    def package(self):
        self._assert_data()

    def package_info(self):
        self._assert_data()
"""
        client.save({"conanfile.py": conanfile,
                     "conandata.yml": """
sources:
  all:
    url: "the url"
    other: "field"
"""})
        ref = ConanFileReference.loads("Lib/0.1@user/testing")
        client.run("create . {}".format(ref))
        self.assertIn("File 'conandata.yml' found. Exporting it...", client.out)
        self.assertIn("My URL:", client.out)
        export_folder = client.cache.package_layout(ref).export()
        self.assertTrue(os.path.exists(os.path.join(export_folder, "conandata.yml")))

        # Transitive loaded?
        client.save({"conanfile.txt": "[requires]\n{}".format(ref)}, clean_first=True)
        client.run("install . ")
        self.assertIn("My URL:", client.out)
        client.run("install . --build")
        self.assertIn("My URL:", client.out)
示例#32
0
    def pythonpath_env_injection_test(self):

        # Save some custom python code in custom dir
        external_py = '''
def external_baz():
    print("External baz")

'''
        external_dir = temp_folder()
        save(os.path.join(external_dir, "external.py"), external_py)

        conanfile = """

import os
from conans import ConanFile, tools

class ConanToolPackage(ConanFile):
    name = "conantool"
    version = "1.0"
    exports = "*"
    build_policy = "missing"

    def build(self):
        with tools.pythonpath(self):
            import external
            external.external_baz()

    def package(self):
        self.copy("*")

    def package_info(self):
        self.env_info.PYTHONPATH.append(self.package_folder)
"""
        client = TestClient()
        client.save({CONANFILE: conanfile, "__init__.py": "", "mytest.py": test})
        client.run("export . lasote/stable")

        # We can't build the package without our PYTHONPATH
        self.assertRaises(Exception, client.run, "install conantool/1.0@lasote/stable --build missing")

        # But we can inject the PYTHONPATH
        client.run("install conantool/1.0@lasote/stable -e PYTHONPATH=['%s']" % external_dir)

        # Now we want to reuse the package and access both external stuff and mytest.py stuff

        reuse = """from conans import ConanFile, tools

class ToolsTest(ConanFile):
    name = "Consumer"
    version = "0.1"
    requires = "conantool/1.0@lasote/stable"

    def build(self):
        with tools.pythonpath(self):
            import mytest
            mytest.foo(self.output)
            import external
            external.external_baz()
"""
        client.save({CONANFILE: reuse})
        client.run("install . --build -e PYTHONPATH=['%s']" % external_dir)
        client.run("build .")
        info = ConanInfo.loads(load(os.path.join(client.current_folder, "conaninfo.txt")))
        pythonpath = info.env_values.env_dicts(None)[1]["PYTHONPATH"]
        self.assertEquals(os.path.normpath(pythonpath[0]), os.path.normpath(external_dir))
        self.assertTrue(len(pythonpath), 2)
示例#33
0
    def errors_test(self):
        client = TestClient()
        client.save({CONANFILE: conanfile, "__init__.py": "", "mytest.py": test})
        client.run("export . lasote/stable")

        client.save({CONANFILE: reuse}, clean_first=True)
        client.run("install .")
        # BUILD_INFO is created by default, remove it to check message
        os.remove(os.path.join(client.current_folder, BUILD_INFO))
        client.run("source .", ignore_error=True)
        # Output in py3 is different, uses single quote
        # Now it works automatically without the env generator file
        self.assertIn("No module named mytest", str(client.user_io.out).replace("'", ""))
示例#34
0
 def test_local_monorepo(self):
     t = TestClient(path_with_spaces=False)
     t.runner("svn co {} .".format(self.url), cwd=t.current_folder)
     self._run_local_test(t, t.current_folder,
                          os.path.join("lib1", self.path_to_conanfile))
示例#35
0
def test_cmake_virtualenv():
    client = TestClient()
    client.run("new hello/0.1 -s")
    client.run("create .")

    cmakewrapper = textwrap.dedent(r"""
        from conans import ConanFile
        import os
        from conans.tools import save, chdir
        class Pkg(ConanFile):
            def package(self):
                with chdir(self.package_folder):
                    save("cmake.bat", "@echo off\necho MYCMAKE WRAPPER!!\ncmake.exe %*")
                    save("cmake.sh", 'echo MYCMAKE WRAPPER!!\ncmake "$@"')
                    os.chmod("cmake.sh", 0o777)

            def package_info(self):
                # Custom buildenv not defined by cpp_info
                self.buildenv_info.prepend_path("PATH", self.package_folder)
            """)
    consumer = textwrap.dedent("""
        from conans import ConanFile
        from conan.tools.cmake import CMake
        class App(ConanFile):
            settings = "os", "arch", "compiler", "build_type"
            exports_sources = "CMakeLists.txt", "main.cpp"
            requires = "hello/0.1"
            build_requires = "cmakewrapper/0.1"
            generators = "CMakeDeps", "CMakeToolchain", "VirtualEnv"
            apply_env = False

            def build(self):
                cmake = CMake(self)
                if self.settings.os != "Windows":
                    cmake._cmake_program = "cmake.sh"  # VERY DIRTY HACK
                cmake.configure()
                cmake.build()
        """)

    cmakelists = textwrap.dedent("""
        cmake_minimum_required(VERSION 3.15)
        project(MyApp CXX)

        find_package(hello)
        add_executable(app main.cpp)
        target_link_libraries(app hello::hello)
        """)

    client.save(
        {
            "cmakewrapper/conanfile.py":
            cmakewrapper,
            "consumer/conanfile.py":
            consumer,
            "consumer/main.cpp":
            gen_function_cpp(name="main", includes=["hello"], calls=["hello"]),
            "consumer/CMakeLists.txt":
            cmakelists
        },
        clean_first=True)

    client.run("create cmakewrapper cmakewrapper/0.1@")
    client.run("create consumer consumer/0.1@")
    assert "MYCMAKE WRAPPER!!" in client.out
    assert "consumer/0.1: Created package" in client.out
示例#36
0
    def find_package_priority_test(self):
        """A package findXXX has priority over the CMake installation one and the curdir one"""
        client = TestClient()
        conanfile = """from conans import ConanFile
class TestConan(ConanFile):
    name = "Zlib"
    version = "0.1"
    exports = "*"

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

"""
        files = {"conanfile.py": conanfile,
                 "FindZLIB.cmake": 'MESSAGE("HELLO FROM THE PACKAGE FIND PACKAGE!")'}
        client.save(files)
        client.run("create . user/channel")

        files = {"CMakeLists.txt": """
set(CMAKE_CXX_COMPILER_WORKS 1)
set(CMAKE_CXX_ABI_COMPILED 1)
project(MyHello CXX)
cmake_minimum_required(VERSION 2.8)
include(${CMAKE_BINARY_DIR}/../conan_paths.cmake)

find_package(ZLIB REQUIRED)

"""}
        build_dir = os.path.join(client.current_folder, "build")
        files["FindZLIB.cmake"] = 'MESSAGE("HELLO FROM THE INSTALL FOLDER!")'
        client.save(files, clean_first=True)
        os.mkdir(build_dir)
        client.run("install Zlib/0.1@user/channel -g cmake_paths")
        ret = client.runner("cmake .. ", cwd=build_dir)
        self.assertEquals(ret, 0)
        self.assertIn("HELLO FROM THE PACKAGE FIND PACKAGE!", client.out)

        # Now consume the zlib package as a require with the cmake_find_package
        # and the "cmake" generator. Should prioritize the one from the package.
        conanfile = """from conans import ConanFile, CMake
class TestConan(ConanFile):
    name = "Consumer"
    version = "0.1"
    exports = "*"
    settings = "compiler", "arch"
    generators = "cmake_find_package", "cmake"
    requires = "Zlib/0.1@user/channel"

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

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

"""
        files = {"conanfile.py": conanfile,
                 "CMakeLists.txt": """
set(CMAKE_CXX_COMPILER_WORKS 1)
set(CMAKE_CXX_ABI_COMPILED 1)
project(MyHello CXX)
cmake_minimum_required(VERSION 2.8)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()

find_package(ZLIB REQUIRED)

"""}
        client.save(files, clean_first=True)
        client.run("create . user/channel")
        self.assertIn("HELLO FROM THE PACKAGE FIND PACKAGE!", client.out)
        self.assertNotIn("Conan: Using autogenerated FindZlib.cmake", client.out)
示例#37
0
 def test_upload_export_pkg(self):
     """
     Package metadata created when doing an export-pkg and then uploading the package works
     """
     server1 = TestServer([("*/*@*/*", "*")], [("*/*@*/*", "*")],
                          users={"lasote": "mypass"})
     servers = OrderedDict()
     servers["server1"] = server1
     client = TestClient(servers=servers)
     client.save({"release/kk.lib": ""})
     client.run("user lasote -r server1 -p mypass")
     client.run("new hello/1.0 --header")
     client.run("export-pkg . user/testing -pf release")
     client.run("upload hello/1.0@user/testing --all -r server1")
     self.assertNotIn(
         "Binary package hello/1.0@user/testing:5%s not found" %
         NO_SETTINGS_PACKAGE_ID, client.out)
     ref = ConanFileReference("hello", "1.0", "user", "testing")
     metadata = client.cache.package_layout(ref).load_metadata()
     self.assertIn(NO_SETTINGS_PACKAGE_ID, metadata.packages)
     self.assertTrue(metadata.packages[NO_SETTINGS_PACKAGE_ID].revision)
示例#38
0
    def basic_source_test(self):
        client = TestClient()
        client.save({CONANFILE: conanfile, "__init__.py": "", "mytest.py": test})
        client.run("export . lasote/stable")

        client.save({CONANFILE: reuse}, clean_first=True)
        client.run("install .")
        client.run("source .")
        self.assertIn("Hello Baz", client.user_io.out)
        self.assertNotIn("Hello Foo", client.user_io.out)
        self.assertNotIn("Hello Bar", client.user_io.out)
        self.assertNotIn("Hello Boom", client.user_io.out)
示例#39
0
    def upload_reuse_test(self):
        server = TestServer()
        servers = {"default": server}
        client = TestClient(servers=servers, users={"default": [("lasote", "mypass")]})
        client.save({CONANFILE: conanfile, "__init__.py": "", "mytest.py": test})
        client.run("export . lasote/stable")

        client.save({CONANFILE: reuse}, clean_first=True)
        client.run("export . lasote/stable")
        client.run("install Consumer/0.1@lasote/stable --build")
        lines = [line.split(":")[1] for line in str(client.user_io.out).splitlines()
                 if line.startswith("Consumer/0.1@lasote/stable: Hello")]
        self.assertEqual([' Hello Baz', ' Hello Foo', ' Hello Boom', ' Hello Bar'],
                         lines)

        client.run("upload conantool/1.0@lasote/stable --all")
        client.run("remove * -f")
        client.run("search")
        self.assertNotIn("lasote/stable", client.user_io.out)
        client.run("export . lasote/stable")
        client.run("install Consumer/0.1@lasote/stable --build")
        lines = [line.split(":")[1] for line in str(client.user_io.out).splitlines()
                 if line.startswith("Consumer/0.1@lasote/stable: Hello")]
        self.assertEqual([' Hello Baz', ' Hello Foo', ' Hello Boom', ' Hello Bar'],
                         lines)
        # Try again, just in case
        client.run("upload conantool/1.0@lasote/stable --all")
        client.run("remove * -f -r=default")
        client.run("upload conantool/1.0@lasote/stable --all")
示例#40
0
    def transitive_flags_test(self):
        client = TestClient()
        client.save({"conanfile.py": conanfile_py})
        client.run("export . lasote/testing")
        client.save({"conanfile.py": chatconanfile_py}, clean_first=True)
        client.run("export . lasote/testing")
        client.save({"conanfile.txt": conanfile.replace("Hello", "Chat"),
                     "CMakeLists.txt": cmake}, clean_first=True)

        client.run('install . -g cmake')
        generator = '-G "Visual Studio 15 Win64"' if platform.system() == "Windows" else ""
        client.run_command("cmake . %s" % generator)
        cmake_cxx_flags = self._get_line(client.out, "CMAKE_CXX_FLAGS")
        self.assertTrue(cmake_cxx_flags.endswith("MyFlag1 MyFlag2 MyChatFlag1 MyChatFlag2"))
        self.assertIn("CONAN_CXX_FLAGS=MyFlag1 MyFlag2 MyChatFlag1 MyChatFlag2",
                      client.out)
示例#41
0
    def flags_test(self):
        client = TestClient()
        client.save({"conanfile.py": conanfile_py})
        client.run("export . lasote/testing")
        client.save({"conanfile.txt": conanfile,
                     "CMakeLists.txt": cmake}, clean_first=True)

        client.run('install . -g cmake')
        generator = '-G "Visual Studio 15 Win64"' if platform.system() == "Windows" else ""
        client.run_command("cmake . %s" % generator)
        cmake_cxx_flags = self._get_line(client.out, "CMAKE_CXX_FLAGS")
        self.assertTrue(cmake_cxx_flags.endswith("MyFlag1 MyFlag2"))
        self.assertIn("CONAN_CXX_FLAGS=MyFlag1 MyFlag2", client.out)
        self.assertIn("CMAKE_C_FLAGS= -load C:\some\path", client.out)
        self.assertIn("CONAN_C_FLAGS=-load C:\some\path ", client.out)
        self.assertIn('CONAN_DEFINES_HELLO=-DMY_DEF=My" \string;-DMY_DEF2=My${} other \string',
                      client.out)
示例#42
0
    def transitive_targets_flags_test(self):
        client = TestClient()
        client.save({"conanfile.py": conanfile_py})
        client.run("export . lasote/testing")
        client.save({"conanfile.py": chatconanfile_py}, clean_first=True)
        client.run("export . lasote/testing")
        cmake_targets = cmake.replace("conan_basic_setup()",
                                      "conan_basic_setup(TARGETS)\n"
                                      "get_target_property(HELLO_FLAGS CONAN_PKG::Hello"
                                      " INTERFACE_COMPILE_OPTIONS)\n"
                                      "get_target_property(CHAT_FLAGS CONAN_PKG::Chat"
                                      " INTERFACE_COMPILE_OPTIONS)\n"
                                      "get_target_property(HELLO_DEFINES CONAN_PKG::Hello"
                                      " INTERFACE_COMPILE_DEFINITIONS)")
        client.save({"conanfile.txt": conanfile.replace("Hello", "Chat"),
                     "CMakeLists.txt": cmake_targets},
                    clean_first=True)

        client.run('install . -g cmake')
        generator = '-G "Visual Studio 15 Win64"' if platform.system() == "Windows" else ""
        client.run_command("cmake . %s" % generator)

        cmake_cxx_flags = self._get_line(client.out, "CMAKE_CXX_FLAGS")
        self.assertNotIn("My", cmake_cxx_flags)
        self.assertIn("CONAN_CXX_FLAGS=MyFlag1 MyFlag2 MyChatFlag1 MyChatFlag2",
                      client.out)
        self.assertIn("HELLO_CXX_FLAGS=-load;C:\some\path;MyFlag1;MyFlag2;"
                      "$<$<CONFIG:Release>:;>;$<$<CONFIG:RelWithDebInfo>:;>;"
                      "$<$<CONFIG:MinSizeRel>:;>;$<$<CONFIG:Debug>:;>", client.out)
        self.assertIn("CHAT_CXX_FLAGS=MyChatFlag1;MyChatFlag2;"
                      "$<$<CONFIG:Release>:;>;$<$<CONFIG:RelWithDebInfo>:;>;"
                      "$<$<CONFIG:MinSizeRel>:;>;$<$<CONFIG:Debug>:;>", client.out)
        self.assertIn('HELLO_DEFINES=MY_DEF=My" \string;MY_DEF2=My${} other \string;', client.out)
示例#43
0
    def cmake_shared_flag_test(self):
        conanfile = """
import os
from conans import ConanFile, CMake

class MyLib(ConanFile):
    name = "MyLib"
    version = "0.1"
    options = {"shared": [True, False]}
    default_options= "shared=%s"
    settings = "arch", "compiler"

    def build(self):
        cmake = CMake(self)
        if self.options.shared:
            assert(cmake.definitions["BUILD_SHARED_LIBS"] ==  "ON")
        else:
            assert(cmake.definitions["BUILD_SHARED_LIBS"] ==  "OFF")
        """
        client = TestClient()
        client.save({"conanfile.py": conanfile % "True"})
        client.run("build .", assert_error=True)

        self.assertIn("conanbuildinfo.txt file not found", client.out)

        client.run("install .")
        client.run("build .")

        client.save({"conanfile.py": conanfile % "False"}, clean_first=True)
        client.run("install .")
        client.run("build .")
示例#44
0
    def std_flag_applied_test(self):
        conanfile = """
import os
from conans import ConanFile, CMake
class MyLib(ConanFile):
    name = "MyLib"
    version = "0.1"
    settings = "arch", "compiler", "cppstd"
    generators = "cmake"

    def build(self):
        cmake = CMake(self)
        cmake.configure()
        cmake.build()
        """
        client = TestClient()
        client.save({"conanfile.py": conanfile,
                     "mylib.cpp": "auto myfunc(){return 3;}",  # c++14 feature
                     "CMakeLists.txt": """
cmake_minimum_required(VERSION 2.8.12)
set(CMAKE_CXX_COMPILER_WORKS 1)
set(CMAKE_CXX_ABI_COMPILED 1)
project(MyHello CXX)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
add_library(mylib mylib.cpp)
target_link_libraries(mylib ${CONAN_LIBS})
"""})

        if platform.system() != "Windows":
            with catch_deprecation_warning(self):
                client.run("install . --install-folder=build -s cppstd=gnu98")
            client.run("build . --build-folder=build", assert_error=True)
            self.assertIn("Error in build()", client.out)

            # Now specify c++14
            with catch_deprecation_warning(self):
                client.run("install . --install-folder=build -s cppstd=gnu14")
            client.run("build . --build-folder=build")
            self.assertIn("CPP STANDARD: 14 WITH EXTENSIONS ON", client.out)
            libname = "libmylib.a" if platform.system() != "Windows" else "mylib.lib"
            libpath = os.path.join(client.current_folder, "build", "lib", libname)
            self.assertTrue(os.path.exists(libpath))

        with catch_deprecation_warning(self):
            client.run("install . --install-folder=build -s cppstd=14")
        client.run("build . --build-folder=build")
        self.assertIn("CPP STANDARD: 14 WITH EXTENSIONS OFF", client.out)
        self.assertNotIn("Conan setting CXX_FLAGS flags", client.out)
        libname = "libmylib.a" if platform.system() != "Windows" else "mylib.lib"
        libpath = os.path.join(client.current_folder, "build", "lib", libname)
        self.assertTrue(os.path.exists(libpath))
示例#45
0
 def test_upload_key_error(self):
     files = {"conanfile.py": GenConanfile("Hello0", "1.2.1")}
     server1 = TestServer([("*/*@*/*", "*")], [("*/*@*/*", "*")],
                          users={"lasote": "mypass"})
     server2 = TestServer([("*/*@*/*", "*")], [("*/*@*/*", "*")],
                          users={"lasote": "mypass"})
     servers = OrderedDict()
     servers["server1"] = server1
     servers["server2"] = server2
     client = TestClient(servers=servers)
     client.save(files)
     client.run("create . user/testing")
     client.run("user lasote -p mypass")
     client.run("user lasote -p mypass -r server2")
     client.run("upload Hello0/1.2.1@user/testing --all -r server1")
     client.run("remove * --force")
     client.run("install Hello0/1.2.1@user/testing -r server1")
     client.run("remote remove server1")
     client.run("upload Hello0/1.2.1@user/testing --all -r server2")
     self.assertNotIn("ERROR: 'server1'", client.out)
示例#46
0
    def fpic_applied_test(self):
        conanfile = """
import os
from conans import ConanFile, CMake
class MyLib(ConanFile):
    name = "MyLib"
    version = "0.1"
    settings = "arch", "compiler"
    options = {"fPIC": [True, False]}
    default_options = "fPIC=False"
    generators = "cmake"
    exports_sources = "CMakeLists.txt"

    def build(self):
        cmake = CMake(self)
        cmake.configure()
"""
        cmakelists = """
cmake_minimum_required(VERSION 2.8.12)
set(CMAKE_CXX_COMPILER_WORKS 1)
set(CMAKE_CXX_ABI_COMPILED 1)
project(MyHello CXX)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
"""
        client = TestClient()
        client.save({"conanfile.py": conanfile,
                     "CMakeLists.txt": cmakelists})

        client.run("create . user/channel -o MyLib:fPIC=True")
        self.assertIn("Conan: Adjusting fPIC flag (ON)", client.out)

        client.run("create . user/channel -o MyLib:fPIC=False")
        self.assertIn("Conan: Adjusting fPIC flag (OFF)", client.out)

        client.save({"conanfile.py": conanfile.replace("fPIC", "fpic")}, clean_first=False)
        client.run("create . user/channel -o MyLib:fpic=True")
        self.assertNotIn("Conan: Adjusting fPIC flag (ON)", client.out)

        # Skip fpic adjustements in basic setup
        tmp = cmakelists.replace("conan_basic_setup()", "conan_basic_setup(SKIP_FPIC)")
        client.save({"CMakeLists.txt": tmp, "conanfile.py": conanfile}, clean_first=True)
        client.run("create . user/channel -o MyLib:fPIC=True")
        self.assertNotIn("Conan: Adjusting fPIC flag", client.out)
示例#47
0
    def basic_package_test(self):
        client = TestClient()
        client.save({CONANFILE: conanfile, "__init__.py": "", "mytest.py": test})
        client.run("export . lasote/stable")

        client.save({CONANFILE: reuse}, clean_first=True)
        client.run("export . lasote/stable")
        client.run("install Consumer/0.1@lasote/stable --build", ignore_error=True)
        lines = [line.split(":")[1] for line in str(client.user_io.out).splitlines()
                 if line.startswith("Consumer/0.1@lasote/stable: Hello")]
        self.assertEqual([' Hello Baz', ' Hello Foo', ' Hello Boom', ' Hello Bar'],
                         lines)
示例#48
0
    def reuse_test(self):
        client = TestClient()
        client.save({CONANFILE: conanfile, "__init__.py": "", "mytest.py": test})
        client.run("export . lasote/stable")

        client.save({CONANFILE: reuse}, clean_first=True)
        client.run("install .")
        self.assertNotIn("Hello Bar", client.user_io.out)  # IMPORTANT!! WTF? Why this test was passing? Why I'm missing?
        self.assertNotIn("Hello Foo", client.user_io.out)
        client.run("build .")
        self.assertNotIn("Hello Bar", client.user_io.out)
        self.assertIn("Hello Foo", client.user_io.out)

        client.run("export . lasote/stable")
        client.run("install Consumer/0.1@lasote/stable --build")
        lines = [line.split(":")[1] for line in str(client.user_io.out).splitlines()
                 if line.startswith("Consumer/0.1@lasote/stable: Hello")]
        self.assertEqual([' Hello Baz', ' Hello Foo', ' Hello Boom', ' Hello Bar'],
                         lines)
示例#49
0
 def test_remote_monorepo_chdir(self):
     t = TestClient(path_with_spaces=False)
     t.runner("svn co {} .".format(self.url), cwd=t.current_folder)
     self._run_remote_test(t, os.path.join(t.current_folder, "lib1"),
                           self.path_to_conanfile)
示例#50
0
 def test_local_root_folder(self):
     t = TestClient(path_with_spaces=False)
     t.runner('git clone "{}" .'.format(self.url), cwd=t.current_folder)
     self._run_local_test(t, t.current_folder, self.path_to_conanfile)
示例#51
0
    def test_conan_data_development_flow(self):
        client = TestClient()
        conanfile = textwrap.dedent("""
            from conans import ConanFile

            class Lib(ConanFile):

                def _assert_data(self):
                    assert(self.conan_data["sources"]["all"]["url"] == "this url")
                    assert(self.conan_data["sources"]["all"]["other"] == "field")
                    self.output.info("My URL: {}".format(self.conan_data["sources"]["all"]["url"]))

                def source(self):
                    self._assert_data()

                def build(self):
                    self._assert_data()

                def package(self):
                    self._assert_data()
            """)
        conandata = textwrap.dedent("""
            sources:
              all:
                url: "this url"
                other: "field"
        """)
        client.save({"conanfile.py": conanfile,
                     "conandata.yml": conandata})
        client.run("source . -sf tmp/source")
        self.assertIn("My URL: this url", client.out)
        client.run("install . -if tmp/install")
        client.run("build . -if tmp/install -bf tmp/build")
        self.assertIn("My URL: this url", client.out)
        client.run("package . -sf tmp/source -if tmp/install -bf tmp/build -pf tmp/package")
        self.assertIn("My URL: this url", client.out)
        client.run("export-pkg . name/version@ -sf tmp/source -if tmp/install -bf tmp/build")
        self.assertIn("My URL: this url", client.out)
示例#52
0
 def test_remote_root_folder(self):
     t = TestClient(path_with_spaces=False)
     t.runner("svn co {}/lib1 .".format(self.url), cwd=t.current_folder)
     self._run_remote_test(t, t.current_folder, self.path_to_conanfile)
示例#53
0
class IOSMesonTestCase(unittest.TestCase):

    _conanfile_py = textwrap.dedent("""
    from conans import ConanFile, tools
    from conan.tools.meson import MesonToolchain


    class App(ConanFile):
        settings = "os", "arch", "compiler", "build_type"
        options = {"shared": [True, False], "fPIC": [True, False]}
        default_options = {"shared": False, "fPIC": True}

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

        def toolchain(self):
            tc = MesonToolchain(self)
            tc.generate()

        def build(self):
            # this will be moved to build helper eventually
            with tools.vcvars(self) if self.settings.compiler == "Visual Studio" else tools.no_op():
                self.run("meson setup --cross-file conan_meson_cross.ini build .")
                self.run("meson compile -C build")
    """)

    _meson_build = textwrap.dedent("""
    project('tutorial', 'cpp')
    add_global_arguments('-DSTRING_DEFINITION="' + get_option('STRING_DEFINITION') + '"',
                         language : 'cpp')
    hello = library('hello', 'hello.cpp')
    executable('demo', 'main.cpp', link_with: hello)
    """)

    _meson_options_txt = textwrap.dedent("""
    option('STRING_DEFINITION', type : 'string', description : 'a string option')
    """)

    def settings(self):
        return [("os", self.os), ("os.version", self.os_version),
                ("arch", self.arch), ("compiler", "apple-clang"),
                ("compiler.version", "12.0"), ("compiler.libcxx", "libc++")]

    def env(self):
        cc = self.xcrun.cc
        cxx = self.xcrun.cxx

        cflags = apple_deployment_target_flag(self.os, self.os_version)
        cflags += " -isysroot " + self.xcrun.sdk_path
        cflags += " -arch " + to_apple_arch(self.arch)
        cxxflags = cflags

        return {'CC': cc, 'CXX': cxx, 'CFLAGS': cflags, 'CXXFLAGS': cxxflags}

    def profile(self):
        template = textwrap.dedent("""
            include(default)
            [settings]
            {settings}
            [env]
            {env}
            """)
        settings = '\n'.join(
            ["%s = %s" % (s[0], s[1]) for s in self.settings()])
        env = '\n'.join(["%s = %s" % (k, v) for k, v in self.env().items()])
        return template.format(settings=settings, env=env)

    @parameterized.expand([('armv8', 'iOS', '10.0', 'iphoneos'),
                           ('armv7', 'iOS', '10.0', 'iphoneos'),
                           ('x86', 'iOS', '10.0', 'iphonesimulator'),
                           ('x86_64', 'iOS', '10.0', 'iphonesimulator')])
    def test_meson_toolchain(self, arch, os_, os_version, sdk):
        self.xcrun = XCRun(None, sdk)
        self.arch = arch
        self.os = os_
        self.os_version = os_version

        hello_h = gen_function_h(name="hello")
        hello_cpp = gen_function_cpp(name="hello",
                                     preprocessor=["STRING_DEFINITION"])
        app = gen_function_cpp(name="main",
                               includes=["hello"],
                               calls=["hello"])

        self.t = TestClient()

        self.t.save({
            "conanfile.py": self._conanfile_py,
            "meson.build": self._meson_build,
            "meson_options.txt": self._meson_options_txt,
            "hello.h": hello_h,
            "hello.cpp": hello_cpp,
            "main.cpp": app,
            "profile_host": self.profile()
        })

        self.t.run(
            "install . --profile:build=default --profile:host=profile_host")

        self.t.run("build .")

        libhello = os.path.join(self.t.current_folder, "build", "libhello.a")
        self.assertTrue(os.path.isfile(libhello))
        demo = os.path.join(self.t.current_folder, "build", "demo")
        self.assertTrue(os.path.isfile(demo))

        lipo = self.xcrun.find('lipo')

        self.t.run_command('"%s" -info "%s"' % (lipo, libhello))
        self.assertIn("architecture: %s" % to_apple_arch(self.arch),
                      self.t.out)

        self.t.run_command('"%s" -info "%s"' % (lipo, demo))
        self.assertIn("architecture: %s" % to_apple_arch(self.arch),
                      self.t.out)
    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"))
示例#55
0
 def test_checksums_metadata(self):
     client = TestClient(default_server_user=True)
     client.save({"conanfile.py": GenConanfile()})
     client.run('create . lib/1.0@user/channel')
     client.run('upload lib/1.0 -c --all -r default')
     ref = ConanFileReference("lib", "1.0", "user", "channel")
     metadata = client.cache.package_layout(ref).load_metadata()
     package_md5 = metadata.packages[NO_SETTINGS_PACKAGE_ID].checksums[
         "conan_package.tgz"]["md5"]
     package_sha1 = metadata.packages[NO_SETTINGS_PACKAGE_ID].checksums[
         "conan_package.tgz"]["sha1"]
     recipe_md5 = metadata.recipe.checksums["conanfile.py"]["md5"]
     recipe_sha1 = metadata.recipe.checksums["conanfile.py"]["sha1"]
     self.assertEqual(package_md5, "25f53ac9685e07815b990e7c6f21bfd0")
     self.assertEqual(package_sha1,
                      "be152c82859285658a06816aaaec529a159c33d3")
     self.assertEqual(recipe_md5, "8eda41e0997f3eacc436fb6c621d7396")
     self.assertEqual(recipe_sha1,
                      "b97d6b26be5bd02252a44c265755f873cf5ec70b")
     client.run('remove * -f')
     client.run('install lib/1.0@user/channel -r default')
     metadata = client.cache.package_layout(ref).load_metadata()
     self.assertEqual(
         metadata.packages[NO_SETTINGS_PACKAGE_ID].
         checksums["conan_package.tgz"]["md5"], package_md5)
     self.assertEqual(
         metadata.packages[NO_SETTINGS_PACKAGE_ID].
         checksums["conan_package.tgz"]["sha1"], package_sha1)
     self.assertEqual(metadata.recipe.checksums["conanfile.py"]["md5"],
                      recipe_md5)
     self.assertEqual(metadata.recipe.checksums["conanfile.py"]["sha1"],
                      recipe_sha1)
示例#56
0
def test_complete():
    client = TestClient()
    client.run("new myopenssl/1.0 -m=v2_cmake")
    client.run("create . -o myopenssl:shared=True")
    client.run("create . -o myopenssl:shared=True -s build_type=Debug")

    mycmake_main = gen_function_cpp(name="main",
                                    msg="mycmake",
                                    includes=["myopenssl"],
                                    calls=["myopenssl"])
    mycmake_conanfile = textwrap.dedent("""
        from conans import ConanFile
        from conan.tools.cmake import CMake
        class App(ConanFile):
            settings = "os", "arch", "compiler", "build_type"
            requires = "myopenssl/1.0"
            default_options = {"myopenssl:shared": True}
            generators = "CMakeDeps", "CMakeToolchain", "VirtualEnv"
            exports = "*"
            apply_env = False

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

            def package(self):
                src = str(self.settings.build_type) if self.settings.os == "Windows" else ""
                self.copy("mycmake*", src=src, dst="bin")

            def package_info(self):
                self.cpp_info.bindirs = ["bin"]
        """)
    mycmake_cmakelists = textwrap.dedent("""
        set(CMAKE_CXX_COMPILER_WORKS 1)
        set(CMAKE_CXX_ABI_COMPILED 1)
        cmake_minimum_required(VERSION 3.15)
        project(MyCmake CXX)

        find_package(myopenssl REQUIRED)
        add_executable(mycmake main.cpp)
        target_link_libraries(mycmake PRIVATE myopenssl::myopenssl)
        """)
    client.save(
        {
            "conanfile.py": mycmake_conanfile,
            "CMakeLists.txt": mycmake_cmakelists,
            "main.cpp": mycmake_main
        },
        clean_first=True)
    client.run("create . mycmake/1.0@")

    mylib = textwrap.dedent(r"""
        from conans import ConanFile
        import os
        from conan.tools.cmake import CMake
        class Pkg(ConanFile):
            settings = "os", "compiler", "build_type", "arch"
            build_requires = "mycmake/1.0"
            requires = "myopenssl/1.0"
            default_options = {"myopenssl:shared": True}
            exports_sources = "CMakeLists.txt", "main.cpp"
            generators = "CMakeDeps", "CMakeToolchain", "VirtualEnv"

            def build(self):
                cmake = CMake(self)
                cmake.configure()
                cmake.build()
                self.run("mycmake")
                self.output.info("RUNNING MYAPP")
                if self.settings.os == "Windows":
                    self.run(os.sep.join([".", str(self.settings.build_type), "myapp"]),
                             env="conanrunenv")
                else:
                    self.run(os.sep.join([".", "myapp"]), env="conanrunenv")
            """)

    cmakelists = textwrap.dedent("""
        set(CMAKE_CXX_COMPILER_WORKS 1)
        set(CMAKE_CXX_ABI_COMPILED 1)
        cmake_minimum_required(VERSION 3.15)
        project(MyApp CXX)

        find_package(myopenssl)
        add_executable(myapp main.cpp)
        target_link_libraries(myapp myopenssl::myopenssl)
        """)

    client.save(
        {
            "conanfile.py":
            mylib,
            "main.cpp":
            gen_function_cpp(name="main",
                             msg="myapp",
                             includes=["myopenssl"],
                             calls=["myopenssl"]),
            "CMakeLists.txt":
            cmakelists
        },
        clean_first=True)

    client.run(
        "create . myapp/0.1@ -s:b build_type=Release -s:h build_type=Debug")
    first, last = str(client.out).split("RUNNING MYAPP")
    assert "mycmake: Release!" in first
    assert "myopenssl/1.0: Hello World Release!" in first

    assert "myapp: Debug!" in last
    assert "myopenssl/1.0: Hello World Debug!" in last
示例#57
0
    def cmake_paths_integration_test(self):
        """First package with own findHello0.cmake file"""
        client = TestClient()
        conanfile = """from conans import ConanFile
class TestConan(ConanFile):
    name = "Hello0"
    version = "0.1"
    exports = "*"

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

"""
        files = {"conanfile.py": conanfile,
                 "FindHello0.cmake": """
SET(Hello0_FOUND 1)
MESSAGE("HELLO FROM THE Hello0 FIND PACKAGE!")
"""}
        client.save(files)
        client.run("create . user/channel")

        # Directly using CMake as a consumer we can find it with the "cmake_paths" generator
        files = {"CMakeLists.txt": """
set(CMAKE_CXX_COMPILER_WORKS 1)
set(CMAKE_CXX_ABI_COMPILED 1)
project(MyHello CXX)
cmake_minimum_required(VERSION 2.8)

find_package(Hello0 REQUIRED)

"""}
        client.save(files, clean_first=True)
        client.run("install Hello0/0.1@user/channel -g cmake_paths")
        self.assertTrue(os.path.exists(os.path.join(client.current_folder,
                                                    "conan_paths.cmake")))
        # Without the toolchain we cannot find the package
        build_dir = os.path.join(client.current_folder, "build")
        os.mkdir(build_dir)
        ret = client.runner("cmake ..", cwd=build_dir)
        shutil.rmtree(build_dir)
        self.assertNotEqual(ret, 0)

        # With the toolchain everything is ok
        os.mkdir(build_dir)
        ret = client.runner("cmake .. -DCMAKE_TOOLCHAIN_FILE=../conan_paths.cmake",
                            cwd=build_dir)
        self.assertEqual(ret, 0)
        self.assertIn("HELLO FROM THE Hello0 FIND PACKAGE!", client.out)

        # Now try without toolchain but including the file
        files = {"CMakeLists.txt": """
set(CMAKE_CXX_COMPILER_WORKS 1)
set(CMAKE_CXX_ABI_COMPILED 1)
project(MyHello CXX)
cmake_minimum_required(VERSION 2.8)
include(${CMAKE_BINARY_DIR}/../conan_paths.cmake)

find_package(Hello0 REQUIRED)

"""}
        client.save(files, clean_first=True)
        os.mkdir(build_dir)
        client.run("install Hello0/0.1@user/channel -g cmake_paths")
        ret = client.runner("cmake .. ", cwd=build_dir)
        self.assertEqual(ret, 0)
        self.assertIn("HELLO FROM THE Hello0 FIND PACKAGE!", client.out)
示例#58
0
    def build_app_test(self, targets):
        client = TestClient()
        conanfile_py = """
from conans import ConanFile

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"
    def package_info(self):
        self.cpp_info.defines = [r'MY_DEF=My${} $string', r'MY_DEF2=My$ other string']
"""
        client.save({"conanfile.py": conanfile_py})
        client.run("create . lasote/testing")
        consumer = """from conans import ConanFile, CMake
import os
class App(ConanFile):
    settings = "os", "compiler", "arch", "build_type"
    requires = "Hello/0.1@lasote/testing"
    generators = "cmake"
    def build(self):
        cmake = CMake(self)
        cmake.configure()
        cmake.build()
        self.run(os.sep.join([".", "bin", "myapp"]))
"""
        cmake_app = """cmake_minimum_required(VERSION 2.8.12)
set(CMAKE_CXX_COMPILER_WORKS 1)
set(CMAKE_CXX_ABI_COMPILED 1)
project(MyHello CXX)

include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup(%s)
add_executable(myapp myapp.cpp)
conan_target_link_libraries(myapp)
""" % ("TARGETS" if targets else "")

        myapp = r"""#include <iostream>
#define STRINGIFY(x) #x
#define STRINGIFYMACRO(y) STRINGIFY(y)
int main(){
    std::cout << "Msg1: " << STRINGIFYMACRO(MY_DEF) << "\n";
    std::cout << "Msg2: " << STRINGIFYMACRO(MY_DEF2) << "\n";
}"""
        client.save({"conanfile.py": consumer,
                     "CMakeLists.txt": cmake_app,
                     "myapp.cpp": myapp
                     }, clean_first=True)
        client.run("install .")
        client.run("build .")
        self.assertIn("Msg1: My${} $string", client.out)
        self.assertIn("Msg2: My$ other string", client.out)
示例#59
0
    def find_package_priority2_test(self):
        """A system findXXX has NOT priority over the install folder one,
        the zlib package do not package findZLIB.cmake"""
        client = TestClient()
        conanfile = """from conans import ConanFile
class TestConan(ConanFile):
    name = "Zlib"
    version = "0.1"
    exports = "*"

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

"""
        files = {"conanfile.py": conanfile}
        client.save(files)
        client.run("create . user/channel")

        files = {"CMakeLists.txt": """
set(CMAKE_CXX_COMPILER_WORKS 1)
set(CMAKE_CXX_ABI_COMPILED 1)
project(MyHello CXX)
cmake_minimum_required(VERSION 2.8)
include(${CMAKE_BINARY_DIR}/../conan_paths.cmake)

find_package(ZLIB REQUIRED)

"""}
        build_dir = os.path.join(client.current_folder, "build")
        files["FindZLIB.cmake"] = 'MESSAGE("HELLO FROM THE INSTALL FOLDER!")'
        client.save(files, clean_first=True)
        os.mkdir(build_dir)
        client.run("install Zlib/0.1@user/channel -g cmake_paths")
        ret = client.runner("cmake .. ", cwd=build_dir)
        self.assertEquals(ret, 0)
        self.assertIn("HELLO FROM THE INSTALL FOLDER!", client.out)
示例#60
0
 def test_upload_login_prompt_disabled_user_authenticated(self):
     #  When user is authenticated, uploads should work even when login prompt has been disabled.
     client = TestClient(default_server_user=True)
     client.save({"conanfile.py": GenConanfile("Hello0", "1.2.1")})
     client.run("config set general.non_interactive=True")
     client.run("create . user/testing")
     client.run("user -c")
     client.run("user user -p password")
     client.run("upload Hello0/1.2.1@user/testing")
     self.assertIn("Uploading conanmanifest.txt", client.out)
     self.assertIn("Uploading conanfile.py", client.out)