def test_apple_arch_flag(): conanfile = ConanFileMock() conanfile.conf = {"tools.apple:sdk_path": "/path/to/sdk"} conanfile.settings_build = MockSettings({ "build_type": "Debug", "os": "Macos", "arch": "x86_64" }) conanfile.settings = MockSettings({ "build_type": "Debug", "os": "iOS", "os.version": "14", "arch": "armv8" }) be = AutotoolsToolchain(conanfile) expected = "-arch arm64" assert be.apple_arch_flag == expected env = be.vars() assert expected in env["CXXFLAGS"] assert expected in env["CFLAGS"] assert expected in env["LDFLAGS"] # Only set when crossbuilding conanfile = ConanFileMock() conanfile.settings = MockSettings({ "build_type": "Debug", "os": "iOS", "os.version": "14", "arch": "armv8" }) be = AutotoolsToolchain(conanfile) assert be.apple_arch_flag is None
def test_find_program(self): # If we add the path, we should found the env/executable instead of ori/executable # Watch out! 'cmd' returns all the paths where the executable is found, so we need to # take into account the first match (iterate in reverse order) generator = VirtualEnvGenerator(ConanFileMock()) generator.env = {"PATH": [self.env_path], } stdout, environment = self._run_virtualenv(generator) cpaths = dict(l.split("=", 1) for l in reversed(stdout.splitlines()) if l.startswith("__conan_")) self.assertEqual(cpaths["__conan_pre_path__"], cpaths["__conan_post_path__"]) self.assertEqual(cpaths["__conan_env_path__"], cpaths["__conan_post_path__"]) epaths = dict(l.split("=", 1) for l in reversed(stdout.splitlines()) if l.startswith("__exec_")) self.assertEqual(epaths["__exec_pre_path__"], epaths["__exec_post_path__"]) self.assertEqual(epaths["__exec_env_path__"], os.path.join(self.env_path, self.app)) # With any other path, we keep finding the original one generator = VirtualEnvGenerator(ConanFileMock()) generator.env = {"PATH": [os.path.join(self.test_folder, "wrong")], } stdout, environment = self._run_virtualenv(generator) epaths = dict(l.split("=", 1) for l in reversed(stdout.splitlines()) if l.startswith("__exec_")) self.assertEqual(epaths["__exec_pre_path__"], epaths["__exec_post_path__"]) self.assertEqual(epaths["__exec_env_path__"], epaths["__exec_post_path__"])
def test_apple_isysrootflag(): """Even when no cross building it is adjusted because it could target a Mac version""" conanfile = ConanFileMock() conanfile.conf = {"tools.apple:sdk_path": "/path/to/sdk"} conanfile.settings_build = MockSettings({ "build_type": "Debug", "os": "Macos", "arch": "x86_64" }) conanfile.settings = MockSettings({ "build_type": "Debug", "os": "iOS", "os.version": "14", "arch": "armv8" }) be = AutotoolsToolchain(conanfile) expected = "-isysroot /path/to/sdk" assert be.apple_isysroot_flag == expected env = be.vars() assert expected in env["CXXFLAGS"] assert expected in env["CFLAGS"] assert expected in env["LDFLAGS"] # Only set when crossbuilding conanfile = ConanFileMock() conanfile.settings = MockSettings({ "build_type": "Debug", "os": "iOS", "os.version": "14", "arch": "armv8" }) be = AutotoolsToolchain(conanfile) assert be.apple_isysroot_flag is None
def test_define_append(): env = Environment(ConanFileMock()) env.define("MyVar", "MyValue") env.append("MyVar", "MyValue1") env.append("MyVar", ["MyValue2", "MyValue3"]) assert env.get("MyVar") == "MyValue MyValue1 MyValue2 MyValue3" env = Environment(ConanFileMock()) env.append("MyVar", "MyValue") env.append("MyVar", "MyValue1") env.define("MyVar", "MyValue2") assert env.get("MyVar") == "MyValue2"
def run_pkg(msg): # FIXME: This only works with ``--install-folder``, layout() will break this cmd_release = environment_wrap_command(ConanFileMock(), "conanrunenv-release-x86_64", "dep_app", cwd=c.current_folder) c.run_command(cmd_release) assert "{}: Release!".format(msg) in c.out cmd_release = environment_wrap_command(ConanFileMock(), "conanrunenv-debug-x86_64", "dep_app", cwd=c.current_folder) c.run_command(cmd_release) assert "{}: Debug!".format(msg) in c.out
def test_profile(): myprofile = textwrap.dedent(""" # define MyVar1 =MyValue1 # append MyVar2+=MyValue2 # multiple append works MyVar2+=MyValue2_2 # prepend MyVar3=+MyValue3 # unset MyVar4=! # Empty MyVar5= # PATHS # define MyPath1=(path)/my/path1 # append MyPath2+=(path)/my/path2 # multiple append works MyPath2+=(path)/my/path2_2 # prepend MyPath3=+(path)/my/path3 # unset MyPath4=! # PER-PACKAGE mypkg*:MyVar2=MyValue2 """) profile_env = ProfileEnvironment.loads(myprofile) env = profile_env.get_profile_env("") env = env.vars(ConanFileMock()) with environment_append({ "MyVar1": "$MyVar1", "MyVar2": "$MyVar2", "MyVar3": "$MyVar3", "MyVar4": "$MyVar4" }): assert env.get("MyVar1") == "MyValue1" assert env.get("MyVar2", "$MyVar2") == '$MyVar2 MyValue2 MyValue2_2' assert env.get("MyVar3", "$MyVar3") == 'MyValue3 $MyVar3' assert env.get("MyVar4") == "" assert env.get("MyVar5") == '' env = profile_env.get_profile_env("mypkg1/1.0") env = env.vars(ConanFileMock()) assert env.get("MyVar1") == "MyValue1" assert env.get("MyVar2", "$MyVar2") == 'MyValue2'
def test_compose_path_combinations(op1, v1, op2, v2, result): env = Environment(ConanFileMock()) if op1 != "unset": getattr(env, op1 + "_path")("MyVar", v1) else: env.unset("MyVar") env2 = Environment(ConanFileMock()) if op2 != "unset": getattr(env2, op2 + "_path")("MyVar", v2) else: env2.unset("MyVar") env.compose_env(env2) assert env._values["MyVar"].get_str(ConanFileMock(), "{name}", pathsep=":") == result
def test_dict_access(): env = Environment() env.append("MyVar", "MyValue", separator="@") ret = env.vars(ConanFileMock()).items() assert dict(ret) == {"MyVar": "MyValue"} env = Environment() env.prepend("MyVar", "MyValue", separator="@") env_vars = env.vars(ConanFileMock()) assert dict(env_vars.items()) == {"MyVar": "MyValue"} assert env_vars["MyVar"] == "MyValue" env2 = Environment() env2.define("MyVar", "MyValue2") env.compose_env(env2) env_vars = env.vars(ConanFileMock()) assert dict(env_vars.items()) == {"MyVar": "MyValue@MyValue2"} with pytest.raises(KeyError): _ = env_vars["Missing"] # With previous values in the environment env = Environment() env.prepend("MyVar", "MyValue", separator="@") old_env = dict(os.environ) os.environ.update({"MyVar": "PreviousValue"}) env_vars = env.vars(ConanFileMock()) try: assert env_vars["MyVar"] == "MyValue@PreviousValue" finally: os.environ.clear() os.environ.update(old_env) env = Environment() env.append_path("MyVar", "MyValue") old_env = dict(os.environ) os.environ.update({"MyVar": "PreviousValue"}) env_vars = env.vars(ConanFileMock()) try: assert env_vars["MyVar"] == "PreviousValue{}MyValue".format(os.pathsep) with env_vars.apply(): assert os.getenv("MyVar") == "PreviousValue{}MyValue".format( os.pathsep) finally: os.environ.clear() os.environ.update(old_env) assert list(env_vars.keys()) == ["MyVar"] assert dict(env_vars.items()) == {"MyVar": "MyValue"}
def test_compose_combinations(op1, v1, s1, op2, v2, s2, result): env = Environment(ConanFileMock()) if op1 != "unset": getattr(env, op1)("MyVar", v1, s1) else: env.unset("MyVar") env2 = Environment(ConanFileMock()) if op2 != "unset": getattr(env2, op2)("MyVar", v2, s2) else: env2.unset("MyVar") env.compose_env(env2) with environment_append({"MyVar": "MyVar"}): assert env.get("MyVar") == result assert env._values["MyVar"].get_str(ConanFileMock(), "{name}") == result
def test_ftp_invalid_auth(self): with pytest.raises(ConanException) as exc: conanfile = ConanFileMock() ftp_download(conanfile, "test.rebex.net", "readme.txt", "demo", "invalid") assert "530 User cannot log in." in str(exc.value) assert not os.path.exists("readme.txt")
def test_download_authorized(self, bottle_server): # Not authorized dest = os.path.join(temp_folder(), "manual.html") conanfile = ConanFileMock() conanfile._conan_requester = requests with pytest.raises(AuthenticationException): download(conanfile, "http://localhost:%s/basic-auth/user/passwd" % bottle_server.port, dest, retry=0, retry_wait=0) # Authorized download(conanfile, "http://localhost:%s/basic-auth/user/passwd" % bottle_server.port, dest, auth=("user", "passwd"), retry=0, retry_wait=0) # Authorized using headers download(conanfile, "http://localhost:%s/basic-auth/user/passwd" % bottle_server.port, dest, headers={"Authorization": "Basic dXNlcjpwYXNzd2Q="}, retry=0, retry_wait=0)
def test_shared_cmake_toolchain(): client = TestClient(default_server_user=True) client.save(pkg_cmake("hello", "0.1")) client.run("create . -o hello:shared=True") client.save(pkg_cmake("chat", "0.1", requires=["hello/0.1"]), clean_first=True) client.run("create . -o chat:shared=True -o hello:shared=True") client.save(pkg_cmake_app("app", "0.1", requires=["chat/0.1"]), clean_first=True) client.run("create . -o chat:shared=True -o hello:shared=True") client.run("upload * --all -c") client.run("remove * -f") client = TestClient(servers=client.servers, users=client.users) client.run( "install app/0.1@ -o chat:shared=True -o hello:shared=True -g VirtualRunEnv" ) conanfile = ConanFileMock() command = environment_wrap_command(conanfile, "conanrun", "app", cwd=client.current_folder) client.run_command(command) assert "main: Release!" in client.out assert "chat: Release!" in client.out assert "hello: Release!" in client.out
def test_pc(self): tmp_dir = temp_folder() filename = os.path.join(tmp_dir, 'libastral.pc') save(filename, libastral_pc) conanfile = ConanFileMock() pkg_config = PkgConfig(conanfile, "libastral", pkg_config_path=tmp_dir) assert pkg_config.provides == "libastral = 6.6.6" assert pkg_config.version == "6.6.6" assert pkg_config.includedirs == ['/usr/local/include/libastral'] assert pkg_config.defines == ['_USE_LIBASTRAL'] assert pkg_config.libs == ['astral', 'm'] assert pkg_config.libdirs == ['/usr/local/lib/libastral'] assert pkg_config.linkflags == ['-Wl,--whole-archive'] assert pkg_config.variables['prefix'] == '/usr/local' cpp_info = NewCppInfo() pkg_config.fill_cpp_info(cpp_info, is_system=False, system_libs=["m"]) assert cpp_info.includedirs == ['/usr/local/include/libastral'] assert cpp_info.defines == ['_USE_LIBASTRAL'] assert cpp_info.libs == ['astral'] assert cpp_info.system_libs == ['m'] assert cpp_info.libdirs == ['/usr/local/lib/libastral'] assert cpp_info.sharedlinkflags == ['-Wl,--whole-archive']
def test_framework_flags_only_for_apple_os(os_): """ Testing GnuDepsFlags attributes exclusively for Apple OS, frameworks and framework_paths """ # Issue: https://github.com/conan-io/conan/issues/10651 # Issue: https://github.com/conan-io/conan/issues/10640 settings = MockSettings({ "build_type": "Release", "compiler": "gcc", "compiler.version": "10.2", "os": os_, "arch": "x86_64" }) conanfile = ConanFileMock() conanfile.settings = settings cpp_info = MagicMock() cpp_info.frameworks = ["Foundation"] cpp_info.frameworkdirs = ["Framework"] gnudepsflags = GnuDepsFlags(conanfile, cpp_info) expected_framework = [] expected_framework_path = [] if is_apple_os(os_): expected_framework = ["-framework Foundation"] expected_framework_path = ["-F Framework"] assert gnudepsflags.frameworks == expected_framework assert gnudepsflags.framework_paths == expected_framework_path
def test_windows_case_insensitive(): # Append and define operation over the same variable in Windows preserve order env = Environment(ConanFileMock()) env.define("MyVar", "MyValueA") env.define("MYVAR", "MyValueB") env.define("MyVar1", "MyValue1A") env.append("MYVAR1", "MyValue1B") folder = temp_folder() display_bat = textwrap.dedent("""\ @echo off echo MyVar=%MyVar%!! echo MyVar1=%MyVar1%!! """) with chdir(folder): env.save_bat("test.bat") save("display.bat", display_bat) cmd = "test.bat && display.bat && deactivate_test.bat && display.bat" out, _ = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).communicate() out = out.decode() assert "MyVar=MyValueB!!" in out assert "MyVar=!!" in out assert "MyVar1=MyValue1A MyValue1B!!" in out assert "MyVar1=!!" in out
def test_list_variable(self): self.assertNotIn("WHATEVER", os.environ) self.assertIn("PATH", os.environ) existing_path = os.environ.get("PATH") # Avoid duplicates in the path existing_path = os.pathsep.join( OrderedDict.fromkeys(existing_path.split(os.pathsep))) generator = VirtualEnvGenerator(ConanFileMock()) generator.env = { "PATH": [os.path.join(self.test_folder, "bin"), r'other\path'], "WHATEVER": ["list", "other"] } _, environment = self._run_virtualenv(generator) self.assertEqual( environment["PATH"], os.pathsep.join([ os.path.join(self.test_folder, "bin"), r'other\path', self.ori_path, existing_path ])) # FIXME: extra separator in Windows extra_separator = os.pathsep if platform.system() == "Windows" else "" self.assertEqual( environment["WHATEVER"], "{}{}{}{}".format("list", os.pathsep, "other", extra_separator))
def test_sdk(): conanfile = ConanFileMock() conf = ConfDefinition() conf.loads("tools.apple:sdk_path=mypath") conanfile.conf = conf conanfile.settings = MockSettings({"os": "Macos", "os.sdk": "macosx"}) xcodebuild = XcodeBuild(conanfile) xcodebuild.build("app.xcodeproj") # sdk_path takes preference assert "SDKROOT=mypath " in conanfile.command conf = ConfDefinition() conanfile.conf = conf xcodebuild = XcodeBuild(conanfile) xcodebuild.build("app.xcodeproj") assert "SDKROOT=macosx " in conanfile.command conanfile.settings = MockSettings({ "os": "Macos", "os.sdk": "macosx", "os.sdk_version": "12.1" }) xcodebuild = XcodeBuild(conanfile) xcodebuild.build("app.xcodeproj") assert "SDKROOT=macosx12.1 " in conanfile.command conanfile.settings = MockSettings({}) xcodebuild = XcodeBuild(conanfile) xcodebuild.build("app.xcodeproj") assert "SDKROOT" not in conanfile.command
def test_single_patch_description(mock_patch_ng): conanfile = ConanFileMock() conanfile.display_name = 'mocked/ref' patch(conanfile, patch_file='patch-file', patch_description='patch_description') assert 'Apply patch: patch_description\n' == str(conanfile.output)
def test_cxx11_abi_define(): conanfile = ConanFileMock() conanfile.settings = MockSettings({ "build_type": "Release", "arch": "x86", "compiler": "gcc", "compiler.libcxx": "libstdc++", "compiler.version": "7.1", "compiler.cppstd": "17" }) be = AutotoolsToolchain(conanfile) assert be.gcc_cxx11_abi == "_GLIBCXX_USE_CXX11_ABI=0" env = be.environment() assert "-D_GLIBCXX_USE_CXX11_ABI=0" in env["CPPFLAGS"] conanfile.settings = MockSettings({ "build_type": "Release", "arch": "x86", "compiler": "gcc", "compiler.libcxx": "libstdc++11", "compiler.version": "7.1", "compiler.cppstd": "17" }) be = AutotoolsToolchain(conanfile) env = be.environment() assert be.gcc_cxx11_abi is None assert "-D_GLIBCXX_USE_CXX11_ABI=0" not in env["CPPFLAGS"]
def test_warn_when_no_triplet(self): conan_file = ConanFileMock() conan_file.deps_cpp_info = self._creat_deps_cpp_info() conan_file.settings = MockSettings({"arch": "UNKNOWN_ARCH", "os": "Linux"}) AutoToolsBuildEnvironment(conan_file) self.assertIn("Unknown 'UNKNOWN_ARCH' machine, Conan doesn't know " "how to translate it to the GNU triplet", conan_file.output)
def test_target_triple(self): conan_file = ConanFileMock() conan_file.deps_cpp_info = self._creat_deps_cpp_info() conan_file.settings = MockSettings({"os_target":"Linux", "arch_target":"x86_64"}) be = AutoToolsBuildEnvironment(conan_file) expected = "x86_64-linux-gnu" self.assertEqual(be.target, expected)
def _get_conanfile(settings, frameworks=False, system_libs=False): conan_file = ConanFileMock() conan_file.settings = settings conan_file.source_folder = "my_cache_source_folder" conan_file.build_folder = "my_cache_build_folder" conan_file.deps_env_info = DepsEnvInfo() conan_file.deps_user_info = DepsUserInfo() conan_file.deps_cpp_info = DepsCppInfo() cpp_info = CppInfo("zlib", "/root") cpp_info.includedirs.append("path/to/include1") cpp_info.libdirs.append("path/to/lib1") cpp_info.libs.append("mylib") cpp_info.bindirs = "path/to/bin1" cpp_info.cflags.append("c_flag1") cpp_info.cxxflags.append("cxx_flag1") cpp_info.defines.append("mydefine1") if system_libs: cpp_info.system_libs.append("system_lib1") if frameworks: cpp_info.frameworks = ["AVFoundation", "VideoToolbox"] cpp_info.frameworkdirs.extend( ['path/to/Frameworks1', 'path/to/Frameworks2']) cpp_info.filter_empty = False conan_file.deps_cpp_info.add("zlib", cpp_info) conan_file.env_info = EnvInfo() return conan_file
def test_complete(client): conanfile = textwrap.dedent(""" import platform from conans import ConanFile class Pkg(ConanFile): requires = "openssl/1.0" build_requires = "mycmake/1.0" apply_env = False def build_requirements(self): self.build_requires("mygtest/1.0", force_host_context=True) def build(self): mybuild_cmd = "mycmake.bat" if platform.system() == "Windows" else "mycmake.sh" self.run(mybuild_cmd, env="conanbuildenv") mytest_cmd = "mygtest.bat" if platform.system() == "Windows" else "mygtest.sh" self.run(mytest_cmd, env="conanrunenv") """) client.save({"conanfile.py": conanfile}) client.run("install . -s:b os=Windows -s:h os=Linux --build=missing") # Run the BUILD environment ext = "bat" if platform.system( ) == "Windows" else "sh" # TODO: Decide on logic .bat vs .sh cmd = environment_wrap_command(ConanFileMock(), "conanbuildenv", "mycmake.{}".format(ext), cwd=client.current_folder) client.run_command(cmd) assert "MYCMAKE=Windows!!" in client.out assert "MYOPENSSL=Windows!!" in client.out # Run the RUN environment cmd = environment_wrap_command( ConanFileMock(), "conanrunenv", "mygtest.{ext} && .{sep}myrunner.{ext}".format(ext=ext, sep=os.sep), cwd=client.current_folder) client.run_command(cmd) assert "MYGTEST=Linux!!" in client.out assert "MYGTESTVAR=MyGTestValueLinux!!" in client.out client.run("build .") assert "MYCMAKE=Windows!!" in client.out assert "MYOPENSSL=Windows!!" in client.out assert "MYGTEST=Linux!!" in client.out
def test_single_no_patchset(monkeypatch): monkeypatch.setattr(patch_ng, "fromfile", lambda _: None) conanfile = ConanFileMock() conanfile.display_name = 'mocked/ref' with pytest.raises(ConanException) as excinfo: patch(conanfile, patch_file='patch-file-failed') assert 'Failed to parse patch: patch-file-failed' == str(excinfo.value)
def test_invalid_target_triple(): conanfile = ConanFileMock() conanfile.settings = MockSettings({"os": "Linux", "arch": "UNKNOWN_ARCH"}) conanfile.settings_build = MockSettings({"os": "Solaris", "arch": "x86"}) with pytest.raises(ConanException) as excinfo: AutotoolsToolchain(conanfile) assert "Unknown 'UNKNOWN_ARCH' machine, Conan doesn't know how " \ "to translate it to the GNU triplet," in str(excinfo)
def test_ftp_invalid_path(self): with pytest.raises(ConanException) as exc: conanfile = ConanFileMock() ftp_download(conanfile, "test.rebex.net", "invalid-file", "demo", "password") assert "550 The system cannot find the file specified." in str( exc.value) assert not os.path.exists("invalid-file")
def test_get_filename_error(self, bottle_server_zip): # Test: File name cannot be deduced from '?file=1' conanfile = ConanFileMock() conanfile._conan_requester = requests with pytest.raises(ConanException) as error: get(conanfile, "http://localhost:%s/?file=1" % bottle_server_zip.port) assert "Cannot deduce file name from the url" in str(error.value)
def test_single_patch_string(mock_patch_ng): conanfile = ConanFileMock() conanfile.display_name = 'mocked/ref' patch(conanfile, patch_string='patch_string') assert mock_patch_ng.string == b'patch_string' assert mock_patch_ng.filename is None assert mock_patch_ng.apply_args == (None, 0, False) assert len(str(conanfile.output)) == 0
def test_conan_run_tests(self): conan_file = ConanFileMock() conan_file.settings = Settings() conan_file.should_test = True meson = Meson(conan_file) with environment_append({"CONAN_RUN_TESTS": "0"}): meson.test() self.assertIsNone(conan_file.command)
def setUpClass(cls): conanfile = ConanFileMock() conanfile.deps_cpp_info["hello"].bin_paths = ["bin1", "bin2"] conanfile.deps_cpp_info["hello"].lib_paths = ["lib1", "lib2"] cls.generator = VirtualRunEnvGenerator(conanfile) cls.generator.output_path = "not-used" cls.result = cls.generator.content