Ejemplo n.º 1
0
 def setUp(self):
     self.tmp_folder = temp_folder()
     self.cache = ClientCache(self.tmp_folder, TestBufferConanOutput())
Ejemplo n.º 2
0
class VCVarsStoreTest(unittest.TestCase):
    output = TestBufferConanOutput()

    def test_81(self):
        settings = Settings.loads(get_default_settings_yml())
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '14'
        settings.arch = 'x86'
        settings.os = 'WindowsStore'
        settings.os.version = '8.1'

        command = tools.vcvars_command(settings, output=self.output)
        self.assertIn('vcvarsall.bat', command)
        self.assertIn('x86', command)
        self.assertIn('store', command)
        self.assertIn('8.1', command)

    def test_10(self):
        sdk_version = tools.find_windows_10_sdk()
        if not sdk_version:
            return

        settings = Settings.loads(get_default_settings_yml())
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '14'
        settings.arch = 'x86'
        settings.os = 'WindowsStore'
        settings.os.version = '10.0'

        command = tools.vcvars_command(settings, output=self.output)
        self.assertIn('vcvarsall.bat', command)
        self.assertIn('x86', command)
        self.assertIn('store', command)
        self.assertIn(sdk_version, command)

    def test_10_custom_winsdk(self):
        settings = Settings.loads(get_default_settings_yml())
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '14'
        settings.arch = 'x86'
        settings.os = 'WindowsStore'
        settings.os.version = '10.0'

        sdk_version = '10.0.18362.0'
        command = tools.vcvars_command(settings,
                                       winsdk_version=sdk_version,
                                       output=self.output)
        self.assertIn('vcvarsall.bat', command)
        self.assertIn('x86', command)
        self.assertIn('store', command)
        self.assertIn(sdk_version, command)

    def test_invalid(self):
        fake_settings_yml = """
        os:
            WindowsStore:
                version: ["666"]
        arch: [x86]
        compiler:
            Visual Studio:
                runtime: [MD, MT, MTd, MDd]
                version: ["8", "9", "10", "11", "12", "14", "15"]

        build_type: [None, Debug, Release]
        """

        settings = Settings.loads(fake_settings_yml)
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '14'
        settings.arch = 'x86'
        settings.os = 'WindowsStore'
        settings.os.version = '666'

        with self.assertRaises(ConanException):
            tools.vcvars_command(settings, output=self.output)
Ejemplo n.º 3
0
 def test_detect_default_profile(self, _):
     output = TestBufferConanOutput()
     with tools.environment_append({"CC": "gcc"}):
         detect_defaults_settings(output, profile_path="~/.conan/profiles/default")
         self.assertIn("conan profile update settings.compiler.libcxx=libstdc++11 default",
                       output)
Ejemplo n.º 4
0
    def test_get_filename_download(self):
        # Create a tar file to be downloaded from server
        with tools.chdir(tools.mkdir_tmp()):
            import tarfile
            tar_file = tarfile.open("sample.tar.gz", "w:gz")
            mkdir("test_folder")
            tar_file.add(os.path.abspath("test_folder"), "test_folder")
            tar_file.close()
            file_path = os.path.abspath("sample.tar.gz")
            assert (os.path.exists(file_path))

        # Instance stoppable thread server and add endpoints
        thread = StoppableThreadBottle()

        @thread.server.get("/this_is_not_the_file_name")
        def get_file():
            return static_file(os.path.basename(file_path),
                               root=os.path.dirname(file_path))

        @thread.server.get("/")
        def get_file2():
            self.assertEqual(request.query["file"], "1")
            return static_file(os.path.basename(file_path),
                               root=os.path.dirname(file_path))

        @thread.server.get("/error_url")
        def error_url():
            from bottle import response
            response.status = 500
            return 'This always fail'

        thread.run_server()

        out = TestBufferConanOutput()
        # Test: File name cannot be deduced from '?file=1'
        with self.assertRaises(ConanException) as error:
            tools.get("http://localhost:%s/?file=1" % thread.port, output=out)
        self.assertIn(
            "Cannot deduce file name from the url: 'http://localhost:{}/?file=1'."
            " Use 'filename' parameter.".format(thread.port),
            str(error.exception))

        # Test: Works with filename parameter instead of '?file=1'
        with tools.chdir(tools.mkdir_tmp()):
            tools.get("http://localhost:%s/?file=1" % thread.port,
                      filename="sample.tar.gz",
                      requester=requests,
                      output=out,
                      retry=0,
                      retry_wait=0)
            self.assertTrue(os.path.exists("test_folder"))

        # Test: Use a different endpoint but still not the filename one
        with tools.chdir(tools.mkdir_tmp()):
            from zipfile import BadZipfile
            with self.assertRaises(BadZipfile):
                tools.get("http://localhost:%s/this_is_not_the_file_name" %
                          thread.port,
                          requester=requests,
                          output=out,
                          retry=0,
                          retry_wait=0)
            tools.get("http://localhost:%s/this_is_not_the_file_name" %
                      thread.port,
                      filename="sample.tar.gz",
                      requester=requests,
                      output=out,
                      retry=0,
                      retry_wait=0)
            self.assertTrue(os.path.exists("test_folder"))
        thread.stop()

        with six.assertRaisesRegex(self, ConanException, "Error"):
            tools.get("http://localhost:%s/error_url" % thread.port,
                      filename="fake_sample.tar.gz",
                      requester=requests,
                      output=out,
                      verify=False,
                      retry=2,
                      retry_wait=0)

        # Not found error
        self.assertEqual(str(out).count("Waiting 0 seconds to retry..."), 2)
Ejemplo n.º 5
0
class ToolsTest(unittest.TestCase):
    output = TestBufferConanOutput()

    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)

    def test_load_save(self):
        folder = temp_folder()
        path = os.path.join(folder, "file")
        save(path, u"äüïöñç")
        content = load(path)
        self.assertEqual(content, u"äüïöñç")

    def test_md5(self):
        result = md5(u"äüïöñç")
        self.assertEqual("dfcc3d74aa447280a7ecfdb98da55174", result)

    def test_cpu_count(self):
        output = ConanOutput(sys.stdout)
        cpus = tools.cpu_count(output=output)
        self.assertIsInstance(cpus, int)
        self.assertGreaterEqual(cpus, 1)
        with tools.environment_append({"CONAN_CPU_COUNT": "34"}):
            self.assertEqual(tools.cpu_count(output=output), 34)
        with tools.environment_append({"CONAN_CPU_COUNT": "null"}):
            with six.assertRaisesRegex(self, ConanException,
                                       "Invalid CONAN_CPU_COUNT value"):
                tools.cpu_count(output=output)

    @patch("conans.client.tools.oss.CpuProperties.get_cpu_period")
    @patch("conans.client.tools.oss.CpuProperties.get_cpu_quota")
    def test_cpu_count_in_container(self, get_cpu_quota_mock,
                                    get_cpu_period_mock):
        get_cpu_quota_mock.return_value = 12000
        get_cpu_period_mock.return_value = 1000

        output = ConanOutput(sys.stdout)
        cpus = tools.cpu_count(output=output)
        self.assertEqual(12, cpus)

    def test_get_env_unit(self):
        """
        Unit tests tools.get_env
        """
        # Test default
        self.assertIsNone(tools.get_env("NOT_DEFINED", environment={}), None)
        # Test defined default
        self.assertEqual(
            tools.get_env("NOT_DEFINED_KEY",
                          default="random_default",
                          environment={}), "random_default")
        # Test return defined string
        self.assertEqual(
            tools.get_env("FROM_STR",
                          default="",
                          environment={"FROM_STR": "test_string_value"}),
            "test_string_value")
        # Test boolean conversion
        self.assertEqual(
            tools.get_env("BOOL_FROM_STR",
                          default=False,
                          environment={"BOOL_FROM_STR": "1"}), True)
        self.assertEqual(
            tools.get_env("BOOL_FROM_STR",
                          default=True,
                          environment={"BOOL_FROM_STR": "0"}), False)
        self.assertEqual(
            tools.get_env("BOOL_FROM_STR",
                          default=False,
                          environment={"BOOL_FROM_STR": "True"}), True)
        self.assertEqual(
            tools.get_env("BOOL_FROM_STR",
                          default=True,
                          environment={"BOOL_FROM_STR": ""}), False)
        # Test int conversion
        self.assertEqual(
            tools.get_env("TO_INT", default=2, environment={"TO_INT": "1"}), 1)
        # Test float conversion
        self.assertEqual(
            tools.get_env("TO_FLOAT",
                          default=2.0,
                          environment={"TO_FLOAT": "1"}), 1.0),
        # Test list conversion
        self.assertEqual(
            tools.get_env("TO_LIST",
                          default=[],
                          environment={"TO_LIST": "1,2,3"}), ["1", "2", "3"])
        self.assertEqual(
            tools.get_env("TO_LIST_NOT_TRIMMED",
                          default=[],
                          environment={"TO_LIST_NOT_TRIMMED": " 1 , 2 , 3 "}),
            ["1", "2", "3"])

    def test_get_env_in_conanfile(self):
        """
        Test get_env is available and working in conanfile
        """
        client = TestClient()

        conanfile = """from conans import ConanFile, tools

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

    def build(self):
        run_tests = tools.get_env("CONAN_RUN_TESTS", default=False)
        print("test_get_env_in_conafile CONAN_RUN_TESTS=%r" % run_tests)
        assert(run_tests == True)
        """
        client.save({"conanfile.py": conanfile})

        with tools.environment_append({"CONAN_RUN_TESTS": "1"}):
            client.run("install .")
            client.run("build .")

    def test_global_tools_overrided(self):
        client = TestClient()

        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("install .")
        client.run("build .")

        # Not test the real commmand get_command if it's setting the module global vars
        tmp = temp_folder()
        conf = get_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()
        global_output, global_requester = get_global_instances()
        self.assertEqual(global_requester.proxies,
                         {"http": "http://myproxy.com"})
        self.assertIsNotNone(global_output.warn)

    def test_environment_nested(self):
        with tools.environment_append({"A": "1", "Z": "40"}):
            with tools.environment_append({"A": "1", "B": "2"}):
                with tools.environment_append({"A": "2", "B": "2"}):
                    self.assertEqual(os.getenv("A"), "2")
                    self.assertEqual(os.getenv("B"), "2")
                    self.assertEqual(os.getenv("Z"), "40")
                self.assertEqual(os.getenv("A", None), "1")
                self.assertEqual(os.getenv("B", None), "2")
            self.assertEqual(os.getenv("A", None), "1")
            self.assertEqual(os.getenv("Z", None), "40")

        self.assertEqual(os.getenv("A", None), None)
        self.assertEqual(os.getenv("B", None), None)
        self.assertEqual(os.getenv("Z", None), None)

    @pytest.mark.skipif(platform.system() != "Windows",
                        reason="Requires vswhere")
    def test_vswhere_description_strip(self):
        myoutput = """
[
  {
    "instanceId": "17609d7c",
    "installDate": "2018-06-11T02:15:04Z",
    "installationName": "VisualStudio/15.7.3+27703.2026",
    "installationPath": "",
    "installationVersion": "15.7.27703.2026",
    "productId": "Microsoft.VisualStudio.Product.Enterprise",
    "productPath": "",
    "isPrerelease": false,
    "displayName": "Visual Studio Enterprise 2017",
    "description": "生産性向上と、さまざまな規模のチーム間の調整のための Microsoft DevOps ソリューション",
    "channelId": "VisualStudio.15.Release",
    "channelUri": "https://aka.ms/vs/15/release/channel",
    "enginePath": "",
    "releaseNotes": "https://go.microsoft.com/fwlink/?LinkId=660692#15.7.3",
    "thirdPartyNotices": "https://go.microsoft.com/fwlink/?LinkId=660708",
    "updateDate": "2018-06-11T02:15:04.7009868Z",
    "catalog": {
      "buildBranch": "d15.7",
      "buildVersion": "15.7.27703.2026",
      "id": "VisualStudio/15.7.3+27703.2026",
      "localBuild": "build-lab",
      "manifestName": "VisualStudio",
      "manifestType": "installer",
      "productDisplayVersion": "15.7.3",
      "productLine": "Dev15",
      "productLineVersion": "2017",
      "productMilestone": "RTW",
      "productMilestoneIsPreRelease": "False",
      "productName": "Visual Studio",
      "productPatchVersion": "3",
      "productPreReleaseMilestoneSuffix": "1.0",
      "productRelease": "RTW",
      "productSemanticVersion": "15.7.3+27703.2026",
      "requiredEngineVersion": "1.16.1187.57215"
    },
    "properties": {
      "campaignId": "",
      "canceled": "0",
      "channelManifestId": "VisualStudio.15.Release/15.7.3+27703.2026",
      "nickname": "",
      "setupEngineFilePath": ""
    }
  },
  {
    "instanceId": "VisualStudio.12.0",
    "installationPath": "",
    "installationVersion": "12.0"
  }
]

"""
        if six.PY3:
            # In python3 the output from subprocess.check_output are bytes, not str
            myoutput = myoutput.encode()
        myrunner = mock_open()
        myrunner.check_output = lambda x: myoutput
        with patch('conans.client.tools.win.subprocess', myrunner):
            json = vswhere()
            self.assertNotIn("descripton", json)

    @pytest.mark.skipif(platform.system() != "Windows",
                        reason="Requires Windows")
    def test_run_in_bash(self):
        class MockConanfile(object):
            def __init__(self):

                self.output = namedtuple("output", "info")(
                    lambda x: None)  # @UnusedVariable
                self.env = {"PATH": "/path/to/somewhere"}

                class MyRun(object):
                    def __call__(self,
                                 command,
                                 output,
                                 log_filepath=None,
                                 cwd=None,
                                 subprocess=False):  # @UnusedVariable
                        self.command = command

                self._conan_runner = MyRun()

        conanfile = MockConanfile()
        with patch.object(OSInfo, "bash_path", return_value='bash'):
            tools.run_in_windows_bash(conanfile,
                                      "a_command.bat",
                                      subsystem="cygwin")
            self.assertIn("bash", conanfile._conan_runner.command)
            self.assertIn("--login -c", conanfile._conan_runner.command)
            self.assertIn("^&^& a_command.bat ^",
                          conanfile._conan_runner.command)

        with tools.environment_append(
            {"CONAN_BASH_PATH": "path\\to\\mybash.exe"}):
            tools.run_in_windows_bash(conanfile,
                                      "a_command.bat",
                                      subsystem="cygwin")
            self.assertIn('path\\to\\mybash.exe --login -c',
                          conanfile._conan_runner.command)

        with tools.environment_append(
            {"CONAN_BASH_PATH": "path with spaces\\to\\mybash.exe"}):
            tools.run_in_windows_bash(conanfile,
                                      "a_command.bat",
                                      subsystem="cygwin",
                                      with_login=False)
            self.assertIn('"path with spaces\\to\\mybash.exe"  -c',
                          conanfile._conan_runner.command)

        # try to append more env vars
        conanfile = MockConanfile()
        with patch.object(OSInfo, "bash_path", return_value='bash'):
            tools.run_in_windows_bash(conanfile,
                                      "a_command.bat",
                                      subsystem="cygwin",
                                      env={
                                          "PATH": "/other/path",
                                          "MYVAR": "34"
                                      })
            self.assertIn(
                '^&^& PATH=\\^"/other/path:/path/to/somewhere:$PATH\\^" '
                '^&^& MYVAR=34 ^&^& a_command.bat ^',
                conanfile._conan_runner.command)

    def test_download_retries_errors(self):
        out = TestBufferConanOutput()

        # Retry arguments override defaults
        with six.assertRaisesRegex(self, ConanException, "Error downloading"):
            tools.download("http://fakeurl3.es/nonexists",
                           os.path.join(temp_folder(), "file.txt"),
                           out=out,
                           requester=requests,
                           retry=2,
                           retry_wait=1)
        self.assertEqual(str(out).count("Waiting 1 seconds to retry..."), 2)

        # Not found error
        with six.assertRaisesRegex(
                self, ConanException,
                "Not found: http://google.es/FILE_NOT_FOUND"):
            tools.download("http://google.es/FILE_NOT_FOUND",
                           os.path.join(temp_folder(), "README.txt"),
                           out=out,
                           requester=requests,
                           retry=2,
                           retry_wait=0)

    @pytest.mark.slow
    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()

    @pytest.mark.slow
    @patch("conans.tools._global_config")
    def test_download_unathorized(self, mock_config):
        http_server = StoppableThreadBottle()
        mock_config.return_value = ConfigMock()

        @http_server.server.get('/forbidden')
        def get_forbidden():
            return HTTPError(403, "Access denied.")

        http_server.run_server()

        out = TestBufferConanOutput()
        dest = os.path.join(temp_folder(), "manual.html")
        # Not authorized
        with six.assertRaisesRegex(self, AuthenticationException, "403"):
            tools.download("http://localhost:%s/forbidden" % http_server.port,
                           dest,
                           requester=requests,
                           out=out)

        http_server.stop()

    @parameterized.expand([
        ["Linux", "x86", None, "x86-linux-gnu"],
        ["Linux", "x86_64", None, "x86_64-linux-gnu"],
        ["Linux", "armv6", None, "arm-linux-gnueabi"],
        ["Linux", "sparc", None, "sparc-linux-gnu"],
        ["Linux", "sparcv9", None, "sparc64-linux-gnu"],
        ["Linux", "mips", None, "mips-linux-gnu"],
        ["Linux", "mips64", None, "mips64-linux-gnu"],
        ["Linux", "ppc32", None, "powerpc-linux-gnu"],
        ["Linux", "ppc64", None, "powerpc64-linux-gnu"],
        ["Linux", "ppc64le", None, "powerpc64le-linux-gnu"],
        ["Linux", "armv5te", None, "arm-linux-gnueabi"],
        ["Linux", "arm_whatever", None, "arm-linux-gnueabi"],
        ["Linux", "armv7hf", None, "arm-linux-gnueabihf"],
        ["Linux", "armv6", None, "arm-linux-gnueabi"],
        ["Linux", "armv7", None, "arm-linux-gnueabi"],
        ["Linux", "armv8_32", None, "aarch64-linux-gnu_ilp32"],
        ["Linux", "armv5el", None, "arm-linux-gnueabi"],
        ["Linux", "armv5hf", None, "arm-linux-gnueabihf"],
        ["Linux", "s390", None, "s390-ibm-linux-gnu"],
        ["Linux", "s390x", None, "s390x-ibm-linux-gnu"],
        ["Android", "x86", None, "i686-linux-android"],
        ["Android", "x86_64", None, "x86_64-linux-android"],
        ["Android", "armv6", None, "arm-linux-androideabi"],
        ["Android", "armv7", None, "arm-linux-androideabi"],
        ["Android", "armv7hf", None, "arm-linux-androideabi"],
        ["Android", "armv8", None, "aarch64-linux-android"],
        ["Windows", "x86", "Visual Studio", "i686-windows-msvc"],
        ["Windows", "x86", "gcc", "i686-w64-mingw32"],
        ["Windows", "x86_64", "gcc", "x86_64-w64-mingw32"],
        ["Darwin", "x86_64", None, "x86_64-apple-darwin"],
        ["Macos", "x86", None, "i686-apple-darwin"],
        ["iOS", "armv7", None, "arm-apple-ios"],
        ["iOS", "x86", None, "i686-apple-ios"],
        ["iOS", "x86_64", None, "x86_64-apple-ios"],
        ["watchOS", "armv7k", None, "arm-apple-watchos"],
        ["watchOS", "armv8_32", None, "aarch64-apple-watchos"],
        ["watchOS", "x86", None, "i686-apple-watchos"],
        ["watchOS", "x86_64", None, "x86_64-apple-watchos"],
        ["tvOS", "armv8", None, "aarch64-apple-tvos"],
        ["tvOS", "armv8.3", None, "aarch64-apple-tvos"],
        ["tvOS", "x86", None, "i686-apple-tvos"],
        ["tvOS", "x86_64", None, "x86_64-apple-tvos"],
        ["Emscripten", "asm.js", None, "asmjs-local-emscripten"],
        ["Emscripten", "wasm", None, "wasm32-local-emscripten"],
        ["AIX", "ppc32", None, "rs6000-ibm-aix"],
        ["AIX", "ppc64", None, "powerpc-ibm-aix"],
        ["Neutrino", "armv7", None, "arm-nto-qnx"],
        ["Neutrino", "armv8", None, "aarch64-nto-qnx"],
        ["Neutrino", "sh4le", None, "sh4-nto-qnx"],
        ["Neutrino", "ppc32be", None, "powerpcbe-nto-qnx"],
        ["Linux", "e2k-v2", None, "e2k-unknown-linux-gnu"],
        ["Linux", "e2k-v3", None, "e2k-unknown-linux-gnu"],
        ["Linux", "e2k-v4", None, "e2k-unknown-linux-gnu"],
        ["Linux", "e2k-v5", None, "e2k-unknown-linux-gnu"],
        ["Linux", "e2k-v6", None, "e2k-unknown-linux-gnu"],
        ["Linux", "e2k-v7", None, "e2k-unknown-linux-gnu"],
    ])
    def test_get_gnu_triplet(self, os, arch, compiler, expected_triplet):
        triplet = tools.get_gnu_triplet(os, arch, compiler)
        self.assertEqual(
            triplet, expected_triplet,
            "triplet did not match for ('%s', '%s', '%s')" %
            (os, arch, compiler))

    def test_get_gnu_triplet_on_windows_without_compiler(self):
        with self.assertRaises(ConanException):
            tools.get_gnu_triplet("Windows", "x86")

    def test_detect_windows_subsystem(self):
        # Don't raise test
        result = OSInfo.detect_windows_subsystem()
        if not OSInfo.bash_path() or platform.system() != "Windows":
            self.assertEqual(None, result)
        else:
            self.assertEqual(str, type(result))

    @pytest.mark.slow
    @pytest.mark.local_bottle
    def test_get_filename_download(self):
        # Create a tar file to be downloaded from server
        with tools.chdir(tools.mkdir_tmp()):
            import tarfile
            tar_file = tarfile.open("sample.tar.gz", "w:gz")
            mkdir("test_folder")
            tar_file.add(os.path.abspath("test_folder"), "test_folder")
            tar_file.close()
            file_path = os.path.abspath("sample.tar.gz")
            assert (os.path.exists(file_path))

        # Instance stoppable thread server and add endpoints
        thread = StoppableThreadBottle()

        @thread.server.get("/this_is_not_the_file_name")
        def get_file():
            return static_file(os.path.basename(file_path),
                               root=os.path.dirname(file_path))

        @thread.server.get("/")
        def get_file2():
            self.assertEqual(request.query["file"], "1")
            return static_file(os.path.basename(file_path),
                               root=os.path.dirname(file_path))

        @thread.server.get("/error_url")
        def error_url():
            from bottle import response
            response.status = 500
            return 'This always fail'

        thread.run_server()

        out = TestBufferConanOutput()
        # Test: File name cannot be deduced from '?file=1'
        with self.assertRaises(ConanException) as error:
            tools.get("http://localhost:%s/?file=1" % thread.port, output=out)
        self.assertIn(
            "Cannot deduce file name from the url: 'http://localhost:{}/?file=1'."
            " Use 'filename' parameter.".format(thread.port),
            str(error.exception))

        # Test: Works with filename parameter instead of '?file=1'
        with tools.chdir(tools.mkdir_tmp()):
            tools.get("http://localhost:%s/?file=1" % thread.port,
                      filename="sample.tar.gz",
                      requester=requests,
                      output=out,
                      retry=0,
                      retry_wait=0)
            self.assertTrue(os.path.exists("test_folder"))

        # Test: Use a different endpoint but still not the filename one
        with tools.chdir(tools.mkdir_tmp()):
            from zipfile import BadZipfile
            with self.assertRaises(BadZipfile):
                tools.get("http://localhost:%s/this_is_not_the_file_name" %
                          thread.port,
                          requester=requests,
                          output=out,
                          retry=0,
                          retry_wait=0)
            tools.get("http://localhost:%s/this_is_not_the_file_name" %
                      thread.port,
                      filename="sample.tar.gz",
                      requester=requests,
                      output=out,
                      retry=0,
                      retry_wait=0)
            self.assertTrue(os.path.exists("test_folder"))
        thread.stop()

        with six.assertRaisesRegex(self, ConanException, "Error"):
            tools.get("http://localhost:%s/error_url" % thread.port,
                      filename="fake_sample.tar.gz",
                      requester=requests,
                      output=out,
                      verify=False,
                      retry=2,
                      retry_wait=0)

        # Not found error
        self.assertEqual(str(out).count("Waiting 0 seconds to retry..."), 2)

    def test_get_unzip_strip_root(self):
        """Test that the strip_root mechanism from the underlying unzip
          is called if I call the tools.get by checking that the exception of an invalid zip to
          flat is raised"""

        zip_folder = temp_folder()

        def mock_download(*args, **kwargs):
            tmp_folder = temp_folder()
            with chdir(tmp_folder):
                ori_files_dir = os.path.join(tmp_folder, "subfolder-1.2.3")
                file1 = os.path.join(ori_files_dir, "file1")
                file2 = os.path.join(ori_files_dir, "folder", "file2")
                # !!! This file is not under the root "subfolder-1.2.3"
                file3 = os.path.join("file3")
                save(file1, "")
                save(file2, "")
                save(file3, "")
                zip_file = os.path.join(zip_folder, "file.zip")
                zipdir(tmp_folder, zip_file)

        with six.assertRaisesRegex(
                self, ConanException, "The zip file contains more than 1 "
                "folder in the root"):
            with patch('conans.client.tools.net.download', new=mock_download):
                with chdir(zip_folder):
                    tools.get("file.zip", strip_root=True)

    @pytest.mark.slow
    @pytest.mark.local_bottle
    def test_get_gunzip(self):
        # Create a tar file to be downloaded from server
        tmp = temp_folder()
        filepath = os.path.join(tmp, "test.txt.gz")
        import gzip
        with gzip.open(filepath, "wb") as f:
            f.write(b"hello world zipped!")

        thread = StoppableThreadBottle()

        @thread.server.get("/test.txt.gz")
        def get_file():
            return static_file(os.path.basename(filepath),
                               root=os.path.dirname(filepath),
                               mimetype="application/octet-stream")

        thread.run_server()

        out = TestBufferConanOutput()
        with tools.chdir(tools.mkdir_tmp()):
            tools.get("http://*****:*****@patch("conans.client.tools.net.unzip")
    def test_get_mirror(self, _):
        """ tools.get must supports a list of URLs. However, only one must be downloaded.
        """
        class MockRequester(object):
            def __init__(self):
                self.count = 0
                self.fail_first = False
                self.fail_all = False

            def get(self, *args, **kwargs):
                self.count += 1
                resp = Response()
                resp._content = b'{"results": []}'
                resp.headers = {"Content-Type": "application/json"}
                resp.status_code = 200
                if (self.fail_first and self.count == 1) or self.fail_all:
                    resp.status_code = 408
                return resp

        file = "test.txt.gz"
        out = TestBufferConanOutput()
        urls = [
            "http://localhost:{}/{}".format(8000 + i, file) for i in range(3)
        ]

        # Only the first file must be downloaded
        with tools.chdir(tools.mkdir_tmp()):
            requester = MockRequester()
            tools.get(urls,
                      requester=requester,
                      output=out,
                      retry=0,
                      retry_wait=0)
            self.assertEqual(1, requester.count)

        # Fail the first, download only the second
        with tools.chdir(tools.mkdir_tmp()):
            requester = MockRequester()
            requester.fail_first = True
            tools.get(urls,
                      requester=requester,
                      output=out,
                      retry=0,
                      retry_wait=0)
            self.assertEqual(2, requester.count)
            self.assertIn(
                "WARN: Could not download from the URL {}: Error 408 downloading file {}."
                " Trying another mirror.".format(urls[0], urls[0]), out)

        # Fail all downloads
        with tools.chdir(tools.mkdir_tmp()):
            requester = MockRequester()
            requester.fail_all = True
            with self.assertRaises(ConanException) as error:
                tools.get(urls,
                          requester=requester,
                          output=out,
                          retry=0,
                          retry_wait=0)
            self.assertEqual(3, requester.count)
            self.assertIn("All downloads from (3) URLs have failed.",
                          str(error.exception))

    def test_check_output_runner(self):
        import tempfile
        original_temp = tempfile.gettempdir()
        patched_temp = os.path.join(original_temp, "dir with spaces")
        payload = "hello world"
        with patch("tempfile.mktemp") as mktemp:
            mktemp.return_value = patched_temp
            output = check_output_runner(["echo", payload],
                                         stderr=subprocess.STDOUT)
            self.assertIn(payload, str(output))

    def test_unix_to_dos_conanfile(self):
        client = TestClient()
        conanfile = """
import os
from conans import ConanFile, tools

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"
    exports_sources = "file.txt"

    def build(self):
        assert("\\r\\n" in tools.load("file.txt"))
        tools.dos2unix("file.txt")
        assert("\\r\\n" not in tools.load("file.txt"))
        tools.unix2dos("file.txt")
        assert("\\r\\n" in tools.load("file.txt"))
"""
        client.save({"conanfile.py": conanfile, "file.txt": "hello\r\n"})
        client.run("create . user/channel")
Ejemplo n.º 6
0
    def test_variables_setup(self):
        conanfile = ConanFile(TestBufferConanOutput(), None)
        conanfile.initialize(Settings({}), EnvValues())

        # Add some cpp_info for dependencies
        ref = ConanFileReference.loads("MyPkg/0.1@lasote/stables")
        cpp_info = CppInfo(ref.name, "dummy_root_folder1")
        cpp_info.defines = ["MYDEFINE1"]
        cpp_info.cflags.append("-Flag1=23")
        cpp_info.version = "1.3"
        cpp_info.description = "My cool description"
        conanfile.deps_cpp_info.add(ref.name, cpp_info)

        ref = ConanFileReference.loads("MyPkg2/0.1@lasote/stables")
        cpp_info = CppInfo(ref.name, "dummy_root_folder2")
        cpp_info.defines = ["MYDEFINE2"]
        cpp_info.version = "2.3"
        cpp_info.exelinkflags = ["-exelinkflag"]
        cpp_info.sharedlinkflags = ["-sharedlinkflag"]
        cpp_info.cxxflags = ["-cxxflag"]
        cpp_info.public_deps = ["MyPkg"]
        conanfile.deps_cpp_info.add(ref.name, cpp_info)

        # Add env_info
        env_info = EnvInfo()
        env_info.VAR1 = "env_info-value1"
        env_info.PATH.append("path-extended")
        conanfile.deps_env_info.update(env_info, "env_info_pkg")

        # Add user_info
        user_info = UserInfo()
        user_info.VAR1 = "user_info-value1"
        conanfile.deps_user_info["user_info_pkg"] = user_info

        # Add user_info_build
        conanfile.user_info_build = DepsUserInfo()
        user_info = UserInfo()
        user_info.VAR1 = "user_info_build-value1"
        conanfile.user_info_build["user_info_build_pkg"] = user_info

        generator = JsonGenerator(conanfile)
        json_out = generator.content
        parsed = json.loads(json_out)

        # Check dependencies
        dependencies = parsed["dependencies"]
        self.assertEqual(len(dependencies), 2)
        my_pkg = dependencies[0]
        self.assertEqual(my_pkg["name"], "MyPkg")
        self.assertEqual(my_pkg["description"], "My cool description")
        self.assertEqual(my_pkg["defines"], ["MYDEFINE1"])

        # Check env_info
        env_info = parsed["deps_env_info"]
        self.assertListEqual(sorted(env_info.keys()), sorted(["VAR1", "PATH"]))
        self.assertEqual(env_info["VAR1"], "env_info-value1")
        self.assertListEqual(env_info["PATH"], ["path-extended"])

        # Check user_info
        user_info = parsed["deps_user_info"]
        self.assertListEqual(list(user_info.keys()), ["user_info_pkg"])
        self.assertListEqual(list(user_info["user_info_pkg"].keys()), ["VAR1"])
        self.assertEqual(user_info["user_info_pkg"]["VAR1"],
                         "user_info-value1")

        # Check user_info_build
        user_info_build = parsed["user_info_build"]
        self.assertListEqual(list(user_info_build.keys()),
                             ["user_info_build_pkg"])
        self.assertListEqual(
            list(user_info_build["user_info_build_pkg"].keys()), ["VAR1"])
        self.assertEqual(user_info_build["user_info_build_pkg"]["VAR1"],
                         "user_info_build-value1")
Ejemplo n.º 7
0
    def test_install_profile_settings(self):
        files = cpp_hello_conan_files("Hello0", "0.1", build=False)

        # Create a profile and use it
        profile_settings = OrderedDict([("compiler", "Visual Studio"),
                                        ("compiler.version", "12"),
                                        ("compiler.runtime", "MD"),
                                        ("arch", "x86")])

        create_profile(self.client.cache.profiles_path,
                       "vs_12_86",
                       settings=profile_settings,
                       package_settings={})

        self.client.cache.default_profile  # Creates default
        tools.replace_in_file(self.client.cache.default_profile_path,
                              "compiler.libcxx",
                              "#compiler.libcxx",
                              strict=False,
                              output=TestBufferConanOutput())

        self.client.save(files)
        self.client.run("export . lasote/stable")
        self.client.run("install . --build missing -pr vs_12_86")
        info = self.client.load("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 = self.client.load("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)

        # Use package settings in profile
        tmp_settings = OrderedDict()
        tmp_settings["compiler"] = "gcc"
        tmp_settings["compiler.libcxx"] = "libstdc++11"
        tmp_settings["compiler.version"] = "4.8"
        package_settings = {"Hello0": tmp_settings}
        create_profile(self.client.cache.profiles_path,
                       "vs_12_86_Hello0_gcc",
                       settings=profile_settings,
                       package_settings=package_settings)
        # Try to override some settings in install command
        self.client.run(
            "install . --build missing -pr vs_12_86_Hello0_gcc -s compiler.version=14"
        )
        info = self.client.load("conaninfo.txt")
        self.assertIn("compiler=gcc", info)
        self.assertIn("compiler.libcxx=libstdc++11", info)

        # If other package is specified compiler is not modified
        package_settings = {"NoExistsRecipe": tmp_settings}
        create_profile(self.client.cache.profiles_path,
                       "vs_12_86_Hello0_gcc",
                       settings=profile_settings,
                       package_settings=package_settings)
        # Try to override some settings in install command
        self.client.run(
            "install . --build missing -pr vs_12_86_Hello0_gcc -s compiler.version=14"
        )
        info = self.client.load("conaninfo.txt")
        self.assertIn("compiler=Visual Studio", info)
        self.assertNotIn("compiler.libcxx", info)

        # Mix command line package settings with profile
        package_settings = {"Hello0": tmp_settings}
        create_profile(self.client.cache.profiles_path,
                       "vs_12_86_Hello0_gcc",
                       settings=profile_settings,
                       package_settings=package_settings)

        # Try to override some settings in install command
        self.client.run(
            "install . --build missing -pr vs_12_86_Hello0_gcc"
            " -s compiler.version=14 -s Hello0:compiler.libcxx=libstdc++")
        info = self.client.load("conaninfo.txt")
        self.assertIn("compiler=gcc", info)
        self.assertNotIn("compiler.libcxx=libstdc++11", info)
        self.assertIn("compiler.libcxx=libstdc++", info)
Ejemplo n.º 8
0
    def test_copy(self):
        output = TestBufferConanOutput()
        userio = MockedBooleanUserIO(True, out=output)
        paths = ClientCache(temp_folder(), output)

        # Create some packages to copy
        ref = ConanFileReference.loads("Hello/0.1@lasote/testing")
        self._create_conanfile(ref, paths)
        self._create_package(ref, "0101001", paths)
        self._create_package(ref, "2222222", paths)

        # Copy all to destination
        package_copy(ref,
                     "lasote/stable", ["0101001", "2222222"],
                     paths,
                     user_io=userio,
                     force=False)
        new_ref = ConanFileReference.loads("Hello/0.1@lasote/stable")
        self._assert_conanfile_exists(new_ref, paths)
        self._assert_package_exists(new_ref, "0101001", paths)
        self._assert_package_exists(new_ref, "2222222", paths)
        self.assertIn(
            "Copied Hello/0.1@lasote/testing to Hello/0.1@lasote/stable",
            output)
        self.assertIn("Copied 0101001 to Hello/0.1@lasote/stable", output)
        self.assertIn("Copied 2222222 to Hello/0.1@lasote/stable", output)

        # Copy again, without force and answering yes
        output._stream.truncate(0)  # Reset output
        package_copy(ref,
                     "lasote/stable", ["0101001", "2222222"],
                     paths,
                     user_io=userio,
                     force=False)
        self.assertIn(
            "Copied Hello/0.1@lasote/testing to Hello/0.1@lasote/stable",
            output)
        self.assertIn("Copied 0101001 to Hello/0.1@lasote/stable", output)
        self.assertIn("Copied 2222222 to Hello/0.1@lasote/stable", output)
        self.assertIn("'Hello/0.1@lasote/stable' already exist. Override?",
                      output)
        self.assertIn("Package '2222222' already exist. Override?", output)
        self.assertIn("Package '0101001' already exist. Override?", output)

        # Now alter the origin and copy again to same destination and confirm the copy
        self._create_conanfile(ref, paths, "new content")
        self._create_package(ref, "0101001", paths, "new lib content")
        self._create_package(ref, "2222222", paths, "new lib content")
        output._stream.truncate(0)  # Reset output
        package_copy(ref,
                     "lasote/stable", ["0101001", "2222222"],
                     paths,
                     user_io=userio,
                     force=False)
        conanfile_content = load(paths.package_layout(new_ref).conanfile())
        self.assertEqual(conanfile_content, "new content")
        pref = PackageReference(new_ref, "0101001")
        package_content = load(
            os.path.join(
                paths.package_layout(new_ref).package(pref), "package.lib"))
        self.assertEqual(package_content, "new lib content")

        # Now we are going to answer always NO to override
        output._stream.truncate(0)  # Reset output
        userio = MockedBooleanUserIO(False, out=output)

        self._create_conanfile(ref, paths, "content22")
        self._create_package(ref, "0101001", paths, "newlib22")
        self._create_package(ref, "2222222", paths, "newlib22")
        package_copy(ref,
                     "lasote/stable", ["0101001", "2222222"],
                     paths,
                     user_io=userio,
                     force=False)
        conanfile_content = load(paths.package_layout(new_ref).conanfile())
        self.assertEqual(conanfile_content, "new content")  # Not content22
        pref = PackageReference(new_ref, "0101001")
        package_content = load(
            os.path.join(
                paths.package_layout(new_ref).package(pref), "package.lib"))
        self.assertEqual(package_content, "new lib content")  # Not newlib22
        # If conanfile is not override it exist
        self.assertNotIn("Package '2222222' already exist. Override?", output)
        self.assertNotIn("Package '0101001' already exist. Override?", output)
        self.assertNotIn("Copied 0101001 to Hello/0.1@lasote/stable", output)
        self.assertNotIn("Copied 2222222 to Hello/0.1@lasote/stable", output)

        # Now override
        output._stream.truncate(0)  # Reset output
        package_copy(ref,
                     "lasote/stable", ["0101001", "2222222"],
                     paths,
                     user_io=userio,
                     force=True)
        self.assertIn("Copied 0101001 to Hello/0.1@lasote/stable", output)
        self.assertIn("Copied 2222222 to Hello/0.1@lasote/stable", output)

        # Now copy just one package to another user/channel
        output._stream.truncate(0)  # Reset output
        package_copy(ref,
                     "pepe/mychannel", ["0101001"],
                     paths,
                     user_io=userio,
                     force=True)
        self.assertIn("Copied 0101001 to Hello/0.1@pepe/mychannel", output)
        self.assertNotIn("Copied 2222222 to Hello/0.1@pepe/mychannel", output)
        new_ref = ConanFileReference.loads("Hello/0.1@pepe/mychannel")
        self._assert_package_exists(new_ref, "0101001", paths)
        self._assert_package_doesnt_exists(new_ref, "2222222", paths)
Ejemplo n.º 9
0
    def test_variables_setup(self):

        conanfile = ConanFile(TestBufferConanOutput(), None)
        conanfile.initialize(Settings({}), EnvValues())

        ref = ConanFileReference.loads("MyPkg/0.1@lasote/stables")
        cpp_info = CppInfo(ref.name, "dummy_root_folder1")
        cpp_info.defines = ["MYDEFINE1"]
        cpp_info.cflags.append("-Flag1=23")
        cpp_info.version = "1.3"
        cpp_info.description = "My cool description"
        cpp_info.libs = ["MyLib1"]
        conanfile.deps_cpp_info.add(ref.name, cpp_info)

        ref = ConanFileReference.loads("MyPkg2/0.1@lasote/stables")
        cpp_info = CppInfo(ref.name, "dummy_root_folder2")
        cpp_info.libs = ["MyLib2"]
        cpp_info.defines = ["MYDEFINE2"]
        cpp_info.version = "2.3"
        cpp_info.exelinkflags = ["-exelinkflag"]
        cpp_info.sharedlinkflags = ["-sharedlinkflag"]
        cpp_info.cxxflags = ["-cxxflag"]
        cpp_info.public_deps = ["MyPkg"]
        cpp_info.libdirs.extend(["Path\\with\\slashes", "regular/path/to/dir"])
        cpp_info.includedirs.extend(
            ["other\\Path\\with\\slashes", "other/regular/path/to/dir"])
        cpp_info.filter_empty = False
        conanfile.deps_cpp_info.add(ref.name, cpp_info)
        generator = BoostBuildGenerator(conanfile)

        self.assertEqual(
            generator.content, """lib MyLib1 :
	: # requirements
	<name>MyLib1
	: # default-build
	: # usage-requirements
	<define>MYDEFINE1
	<cflags>-Flag1=23
	;

lib MyLib2 :
	: # requirements
	<name>MyLib2
	<search>dummy_root_folder2/lib
	<search>dummy_root_folder2/Path/with/slashes
	<search>dummy_root_folder2/regular/path/to/dir
	: # default-build
	: # usage-requirements
	<define>MYDEFINE2
	<include>dummy_root_folder2/include
	<include>dummy_root_folder2/other/Path/with/slashes
	<include>dummy_root_folder2/other/regular/path/to/dir
	<cxxflags>-cxxflag
	<ldflags>-sharedlinkflag
	;

alias conan-deps :
	MyLib1
	MyLib2
;
""")
Ejemplo n.º 10
0
 def setUp(self):
     self.target = tempfile.mktemp()
     self.out = TestBufferConanOutput()
Ejemplo n.º 11
0
class VCVarsArchTest(unittest.TestCase):
    output = TestBufferConanOutput()

    def assert_vcvars_command(self, settings, expected, output=None, **kwargs):
        output = output or self.output
        command = tools.vcvars_command(settings, output=output, **kwargs)
        command = command.replace('"', '').replace("'", "")
        self.assertTrue(command.endswith('vcvarsall.bat %s' % expected),
                        msg="'{}' doesn't ends with 'vcvarsall.bat {}'".format(
                            command, expected))

    def test_arch(self):
        settings = Settings.loads(get_default_settings_yml())
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '14'

        settings.arch = 'x86'
        self.assert_vcvars_command(settings, "x86")
        with environment_append({"PreferredToolArchitecture": "x64"}):
            self.assert_vcvars_command(settings, "amd64_x86")

        settings.arch = 'x86_64'
        self.assert_vcvars_command(settings, "amd64")

        settings.arch = 'armv7'
        self.assert_vcvars_command(settings, "amd64_arm")

        settings.arch = 'armv8'
        self.assert_vcvars_command(settings, "amd64_arm64")

        settings.arch = 'mips'
        with self.assertRaises(ConanException):
            tools.vcvars_command(settings, output=self.output)

        settings.arch_build = 'x86_64'
        settings.arch = 'x86'
        self.assert_vcvars_command(settings, "amd64_x86")

    def test_arch_override(self):
        settings = Settings.loads(get_default_settings_yml())
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '14'
        settings.arch = 'mips64'

        self.assert_vcvars_command(settings, "x86", arch='x86')
        self.assert_vcvars_command(settings, "amd64", arch='x86_64')
        self.assert_vcvars_command(settings, "amd64_arm", arch='armv7')
        self.assert_vcvars_command(settings, "amd64_arm64", arch='armv8')

        with self.assertRaises(ConanException):
            tools.vcvars_command(settings, arch='mips', output=self.output)

    def test_vcvars_ver_override(self):
        settings = Settings.loads(get_default_settings_yml())
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '15'
        settings.arch = 'x86_64'

        command = tools.vcvars_command(settings,
                                       vcvars_ver='14.14',
                                       output=self.output)
        self.assertIn('vcvarsall.bat', command)
        self.assertIn('-vcvars_ver=14.14', command)

        settings.compiler.version = '14'

        command = tools.vcvars_command(settings,
                                       vcvars_ver='14.14',
                                       output=self.output)
        self.assertIn('vcvarsall.bat', command)
        self.assertIn('-vcvars_ver=14.14', command)

    def test_winsdk_version_override(self):
        settings = Settings.loads(get_default_settings_yml())
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '15'
        settings.arch = 'x86_64'

        command = tools.vcvars_command(settings,
                                       winsdk_version='8.1',
                                       output=self.output)
        self.assertIn('vcvarsall.bat', command)
        self.assertIn('8.1', command)

        settings.compiler.version = '14'

        command = tools.vcvars_command(settings,
                                       winsdk_version='8.1',
                                       output=self.output)
        self.assertIn('vcvarsall.bat', command)
        self.assertIn('8.1', command)

    def test_windows_ce(self):
        settings = Settings.loads(get_default_settings_yml())
        settings.os = 'WindowsCE'
        settings.compiler = 'Visual Studio'
        settings.compiler.version = '15'
        settings.arch = 'armv4i'
        self.assert_vcvars_command(settings, "x86")
Ejemplo n.º 12
0
 def setUp(self):
     self.f = tempfile.mktemp()
     save(self.f, "some contents")
     self.out = TestBufferConanOutput()
Ejemplo n.º 13
0
 def setUp(self):
     self.output = TestBufferConanOutput()
     cache_folder = temp_folder()
     cache = ClientCache(cache_folder, self.output)
     self.cache = cache
Ejemplo n.º 14
0
 def test_detect_abs_file_profile(self, _):
     output = TestBufferConanOutput()
     with tools.environment_append({"CC": "gcc"}):
         detect_defaults_settings(output, profile_path="/foo/bar/quz/custom-profile")
         self.assertIn("conan profile update settings.compiler.libcxx=libstdc++11 "
                       "custom-profile", output)
Ejemplo n.º 15
0
    def log_test(self):
        conanfile = '''
from conans import ConanFile

class ConanFileToolsTest(ConanFile):
    def build(self):
        self.run("cmake --version")
'''
        # A runner logging everything
        output = TestBufferConanOutput()
        runner = ConanRunner(print_commands_to_output=True,
                             generate_run_log_file=True,
                             log_run_to_output=True,
                             output=output)
        self._install_and_build(conanfile, runner=runner)
        self.assertIn("--Running---", output)
        self.assertIn("> cmake --version", output)
        self.assertIn("cmake version", output)
        self.assertIn("Logging command output to file ", output)

        # A runner logging everything
        output = TestBufferConanOutput()
        runner = ConanRunner(print_commands_to_output=True,
                             generate_run_log_file=False,
                             log_run_to_output=True,
                             output=output)
        self._install_and_build(conanfile, runner=runner)
        self.assertIn("--Running---", output)
        self.assertIn("> cmake --version", output)
        self.assertIn("cmake version", output)
        self.assertNotIn("Logging command output to file ", output)

        output = TestBufferConanOutput()
        runner = ConanRunner(print_commands_to_output=False,
                             generate_run_log_file=True,
                             log_run_to_output=True,
                             output=output)
        self._install_and_build(conanfile, runner=runner)
        self.assertNotIn("--Running---", output)
        self.assertNotIn("> cmake --version", output)
        self.assertIn("cmake version", output)
        self.assertIn("Logging command output to file ", output)

        output = TestBufferConanOutput()
        runner = ConanRunner(print_commands_to_output=False,
                             generate_run_log_file=False,
                             log_run_to_output=True,
                             output=output)
        self._install_and_build(conanfile, runner=runner)
        self.assertNotIn("--Running---", output)
        self.assertNotIn("> cmake --version", output)
        self.assertIn("cmake version", output)
        self.assertNotIn("Logging command output to file ", output)

        output = TestBufferConanOutput()
        runner = ConanRunner(print_commands_to_output=False,
                             generate_run_log_file=False,
                             log_run_to_output=False,
                             output=output)
        self._install_and_build(conanfile, runner=runner)
        self.assertNotIn("--Running---", output)
        self.assertNotIn("> cmake --version", output)
        self.assertNotIn("cmake version", output)
        self.assertNotIn("Logging command output to file ", output)

        output = TestBufferConanOutput()
        runner = ConanRunner(print_commands_to_output=False,
                             generate_run_log_file=True,
                             log_run_to_output=False,
                             output=output)
        self._install_and_build(conanfile, runner=runner)
        self.assertNotIn("--Running---", output)
        self.assertNotIn("> cmake --version", output)
        self.assertNotIn("cmake version", output)
        self.assertIn("Logging command output to file ", output)
Ejemplo n.º 16
0
 def cache(self):
     # Returns a temporary cache object intended for inspecting it
     return ClientCache(self.cache_folder, TestBufferConanOutput())
Ejemplo n.º 17
0
 def test_detect_clang_gcc_toolchain(self, _):
     output = TestBufferConanOutput()
     with tools.environment_append(
         {"CC": "clang-9 --gcc-toolchain=/usr/lib/gcc/x86_64-linux-gnu/9"}):
         detect_defaults_settings(output, profile_path="./MyProfile")
         self.assertIn("CC and CXX: clang-9 --gcc-toolchain", output)
Ejemplo n.º 18
0
 def setUp(self):
     d = tempfile.mkdtemp()
     self.target = os.path.join(d, "target")
     self.out = TestBufferConanOutput()
Ejemplo n.º 19
0
 def setUp(self):
     self.out = TestBufferConanOutput()
Ejemplo n.º 20
0
    def test_variables_setup(self):
        tmp_folder1 = temp_folder()
        tmp_folder2 = temp_folder()
        save(os.path.join(tmp_folder1, "include1", "file.h"), "")
        save(os.path.join(tmp_folder2, "include2", "file.h"), "")
        save(os.path.join(tmp_folder1, "lib1", "file.a"), "")
        save(os.path.join(tmp_folder2, "lib2", "file.a"), "")
        save(os.path.join(tmp_folder1, "bin1", "file.bin"), "")
        save(os.path.join(tmp_folder2, "bin2", "file.bin"), "")
        save(os.path.join(tmp_folder1, "SystemFrameworks", "file.bin"), "")

        conanfile = ConanFile(TestBufferConanOutput(), None)
        conanfile.initialize(Settings({}), EnvValues())
        ref = ConanFileReference.loads("MyPkg1/0.1@lasote/stables")
        cpp_info = CppInfo(ref.name, tmp_folder1)
        cpp_info.defines = ["MYDEFINE1"]
        cpp_info.includedirs = ['include1']
        cpp_info.libdirs = ['lib1']
        cpp_info.libs = ['libfoo']
        cpp_info.bindirs = ['bin1']
        cpp_info.version = "0.1"
        cpp_info.cflags = ['-fgimple']
        cpp_info.cxxflags = ['-fdollars-in-identifiers']
        cpp_info.sharedlinkflags = ['-framework Cocoa']
        cpp_info.exelinkflags = ['-framework QuartzCore']
        cpp_info.frameworks = ['AudioUnit']
        cpp_info.frameworkdirs = ['SystemFrameworks']
        cpp_info.system_libs = ["system_lib1"]
        conanfile.deps_cpp_info.add(ref.name, cpp_info)
        ref = ConanFileReference.loads("MyPkg2/3.2.3@lasote/stables")
        cpp_info = CppInfo(ref.name, tmp_folder2)
        cpp_info.defines = ["MYDEFINE2"]
        cpp_info.includedirs = ['include2']
        cpp_info.libdirs = ['lib2']
        cpp_info.libs = ['libbar']
        cpp_info.bindirs = ['bin2']
        cpp_info.version = "3.2.3"
        cpp_info.cflags = ['-fno-asm']
        cpp_info.cxxflags = ['-pthread']
        cpp_info.sharedlinkflags = ['-framework AudioFoundation']
        cpp_info.exelinkflags = ['-framework VideoToolbox']
        cpp_info.system_libs = ["system_lib2"]
        conanfile.deps_cpp_info.add(ref.name, cpp_info)
        generator = MakeGenerator(conanfile)
        content = generator.content

        content_template = """
CONAN_ROOT_MYPKG1 ?=  \\
{conan_root_mypkg1}

CONAN_SYSROOT_MYPKG1 ?=  \\


CONAN_INCLUDE_DIRS_MYPKG1 +=  \\
{conan_include_dirs_mypkg1}

CONAN_LIB_DIRS_MYPKG1 +=  \\
{conan_lib_dirs_mypkg1}

CONAN_BIN_DIRS_MYPKG1 +=  \\
{conan_bin_dirs_mypkg1}

CONAN_BUILD_DIRS_MYPKG1 +=  \\
{conan_build_dirs_mypkg1}

CONAN_RES_DIRS_MYPKG1 +=  \\


CONAN_LIBS_MYPKG1 +=  \\
libfoo

CONAN_SYSTEM_LIBS_MYPKG1 +=  \\
system_lib1

CONAN_DEFINES_MYPKG1 +=  \\
MYDEFINE1

CONAN_CFLAGS_MYPKG1 +=  \\
-fgimple

CONAN_CXXFLAGS_MYPKG1 +=  \\
-fdollars-in-identifiers

CONAN_SHAREDLINKFLAGS_MYPKG1 +=  \\
-framework Cocoa

CONAN_EXELINKFLAGS_MYPKG1 +=  \\
-framework QuartzCore

CONAN_FRAMEWORKS_MYPKG1 +=  \\
AudioUnit

CONAN_FRAMEWORK_PATHS_MYPKG1 +=  \\
{conan_framework_dirs_mypkg1}

CONAN_ROOT_MYPKG2 ?=  \\
{conan_root_mypkg2}

CONAN_SYSROOT_MYPKG2 ?=  \\


CONAN_INCLUDE_DIRS_MYPKG2 +=  \\
{conan_include_dirs_mypkg2}

CONAN_LIB_DIRS_MYPKG2 +=  \\
{conan_lib_dirs_mypkg2}

CONAN_BIN_DIRS_MYPKG2 +=  \\
{conan_bin_dirs_mypkg2}

CONAN_BUILD_DIRS_MYPKG2 +=  \\
{conan_build_dirs_mypkg2}

CONAN_RES_DIRS_MYPKG2 +=  \\


CONAN_LIBS_MYPKG2 +=  \\
libbar

CONAN_SYSTEM_LIBS_MYPKG2 +=  \\
system_lib2

CONAN_DEFINES_MYPKG2 +=  \\
MYDEFINE2

CONAN_CFLAGS_MYPKG2 +=  \\
-fno-asm

CONAN_CXXFLAGS_MYPKG2 +=  \\
-pthread

CONAN_SHAREDLINKFLAGS_MYPKG2 +=  \\
-framework AudioFoundation

CONAN_EXELINKFLAGS_MYPKG2 +=  \\
-framework VideoToolbox

CONAN_FRAMEWORKS_MYPKG2 +=  \\


CONAN_FRAMEWORK_PATHS_MYPKG2 +=  \\


CONAN_ROOTPATH +=  \\
$(CONAN_ROOTPATH_MYPKG1) \\
$(CONAN_ROOTPATH_MYPKG2)

CONAN_SYSROOT +=  \\
$(CONAN_SYSROOT_MYPKG1) \\
$(CONAN_SYSROOT_MYPKG2)

CONAN_INCLUDE_DIRS +=  \\
$(CONAN_INCLUDE_DIRS_MYPKG1) \\
$(CONAN_INCLUDE_DIRS_MYPKG2)

CONAN_LIB_DIRS +=  \\
$(CONAN_LIB_DIRS_MYPKG1) \\
$(CONAN_LIB_DIRS_MYPKG2)

CONAN_BIN_DIRS +=  \\
$(CONAN_BIN_DIRS_MYPKG1) \\
$(CONAN_BIN_DIRS_MYPKG2)

CONAN_BUILD_DIRS +=  \\
$(CONAN_BUILD_DIRS_MYPKG1) \\
$(CONAN_BUILD_DIRS_MYPKG2)

CONAN_RES_DIRS +=  \\
$(CONAN_RES_DIRS_MYPKG1) \\
$(CONAN_RES_DIRS_MYPKG2)

CONAN_LIBS +=  \\
$(CONAN_LIBS_MYPKG1) \\
$(CONAN_LIBS_MYPKG2)

CONAN_DEFINES +=  \\
$(CONAN_DEFINES_MYPKG1) \\
$(CONAN_DEFINES_MYPKG2)

CONAN_CFLAGS +=  \\
$(CONAN_CFLAGS_MYPKG1) \\
$(CONAN_CFLAGS_MYPKG2)

CONAN_CXXFLAGS +=  \\
$(CONAN_CXXFLAGS_MYPKG1) \\
$(CONAN_CXXFLAGS_MYPKG2)

CONAN_SHAREDLINKFLAGS +=  \\
$(CONAN_SHAREDLINKFLAGS_MYPKG1) \\
$(CONAN_SHAREDLINKFLAGS_MYPKG2)

CONAN_EXELINKFLAGS +=  \\
$(CONAN_EXELINKFLAGS_MYPKG1) \\
$(CONAN_EXELINKFLAGS_MYPKG2)

CONAN_FRAMEWORKS +=  \\
$(CONAN_FRAMEWORKS_MYPKG1) \\
$(CONAN_FRAMEWORKS_MYPKG2)

CONAN_FRAMEWORK_PATHS +=  \\
$(CONAN_FRAMEWORK_PATHS_MYPKG1) \\
$(CONAN_FRAMEWORK_PATHS_MYPKG2)
"""
        root1 = tmp_folder1.replace('\\', '/')
        root2 = tmp_folder2.replace('\\', '/')

        inc1 = os.path.join(tmp_folder1, 'include1').replace('\\', '/')
        inc2 = os.path.join(tmp_folder2, 'include2').replace('\\', '/')

        lib1 = os.path.join(tmp_folder1, 'lib1').replace('\\', '/')
        lib2 = os.path.join(tmp_folder2, 'lib2').replace('\\', '/')

        bin1 = os.path.join(tmp_folder1, 'bin1').replace('\\', '/')
        bin2 = os.path.join(tmp_folder2, 'bin2').replace('\\', '/')

        expected_content = content_template.format(
            conan_root_mypkg1=root1,
            conan_include_dirs_mypkg1=inc1,
            conan_lib_dirs_mypkg1=lib1,
            conan_bin_dirs_mypkg1=bin1,
            conan_build_dirs_mypkg1=root1 + "/",
            conan_root_mypkg2=root2,
            conan_include_dirs_mypkg2=inc2,
            conan_lib_dirs_mypkg2=lib2,
            conan_bin_dirs_mypkg2=bin2,
            conan_build_dirs_mypkg2=root2 + "/",
            conan_framework_dirs_mypkg1=root1 + "/SystemFrameworks")
        self.maxDiff = None
        self.assertIn(expected_content, content)
Ejemplo n.º 21
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()
Ejemplo n.º 22
0
    def test_complete(self):
        """ basic installation of a new conans
        """
        client = TestClient()
        files = cpp_hello_source_files()

        ref = ConanFileReference.loads("Hello/1.2.1@frodo/stable")
        reg_folder = client.cache.package_layout(ref).export()

        client.save(files, path=reg_folder)
        client.save(
            {
                CONANFILE: myconan1,
                "infos/%s" % CONANINFO: "//empty",
                "include/no_copy/lib0.h": "NO copy",
                "include/math/lib1.h": "copy",
                "include/math/lib2.h": "copy",
                "include/physics/lib.hpp": "copy",
                "my_lib/debug/libd.a": "copy",
                "my_data/readme.txt": "copy",
                "my_data/readme.md": "NO copy",
                "contrib/math/math.h": "copy",
                "contrib/physics/gravity.h": "copy",
                "contrib/contrib.h": "copy",
                "include/opencv/opencv.hpp": "copy",
                "include/opencv2/opencv2.hpp": "copy",
                "modules/simu/src/simu.cpp": "NO copy",
                "modules/simu/include/opencv2/simu/simu.hpp": "copy",
                "modules/3D/doc/readme.md": "NO copy",
                "modules/3D/include/opencv2/3D/3D.hpp": "copy",
                "modules/dev/src/dev.cpp": "NO copy",
                "modules/dev/include/opencv2/dev/dev.hpp": "copy",
                "modules/opencv_mod.hpp": "copy"
            },
            path=reg_folder)

        conanfile_path = os.path.join(reg_folder, CONANFILE)
        pref = PackageReference(ref, "myfakeid")
        build_folder = client.cache.package_layout(pref.ref).build(pref)
        package_folder = client.cache.package_layout(pref.ref).package(pref)
        install_folder = os.path.join(build_folder, "infos")

        shutil.copytree(reg_folder, build_folder)

        loader = ConanFileLoader(None, TestBufferConanOutput(),
                                 ConanPythonRequire(None, None))
        conanfile = loader.load_consumer(conanfile_path, create_profile())

        run_package_method(conanfile,
                           None,
                           build_folder,
                           build_folder,
                           package_folder,
                           install_folder,
                           Mock(),
                           conanfile_path,
                           ref,
                           copy_info=True)

        # test build folder
        self.assertTrue(os.path.exists(build_folder))
        self.assertTrue(os.path.exists(os.path.join(package_folder,
                                                    CONANINFO)))

        # test pack folder
        self.assertTrue(os.path.exists(package_folder))

        def exist(rel_path):
            return os.path.exists(os.path.join(package_folder, rel_path))

        # Expected files
        self.assertTrue(exist("include/lib1.h"))
        self.assertTrue(exist("include/lib2.h"))
        self.assertTrue(exist("include/physics/lib.hpp"))
        self.assertTrue(exist("include/contrib/math/math.h"))
        self.assertTrue(exist("include/contrib/physics/gravity.h"))
        self.assertTrue(exist("include/contrib/contrib.h"))
        self.assertTrue(exist("include/opencv/opencv.hpp"))
        self.assertTrue(exist("include/opencv2/opencv2.hpp"))
        self.assertTrue(exist("include/opencv2/simu/simu.hpp"))
        self.assertTrue(exist("include/opencv2/3D/3D.hpp"))
        self.assertTrue(exist("include/opencv2/dev/dev.hpp"))
        self.assertTrue(exist("lib/my_lib/libd.a"))
        self.assertTrue(exist("res/shares/readme.txt"))

        # Not expected files
        self.assertFalse(exist("include/opencv2/opencv_mod.hpp"))
        self.assertFalse(exist("include/opencv2/simu.hpp"))
        self.assertFalse(exist("include/opencv2/3D.hpp"))
        self.assertFalse(exist("include/opencv2/dev.hpp"))
        self.assertFalse(exist("include/modules/simu/src/simu.cpp"))
        self.assertFalse(exist("include/modules/3D/doc/readme.md"))
        self.assertFalse(exist("include/modules/dev/src/dev.cpp"))
        self.assertFalse(exist("include/opencv2/opencv_mod.hpp"))
        self.assertFalse(exist("include/include/no_copy/lib0.h"))
        self.assertFalse(exist("res/my_data/readme.md"))
Ejemplo n.º 23
0
    def test_get_mirror(self, _):
        """ tools.get must supports a list of URLs. However, only one must be downloaded.
        """
        class MockRequester(object):
            def __init__(self):
                self.count = 0
                self.fail_first = False
                self.fail_all = False

            def get(self, *args, **kwargs):
                self.count += 1
                resp = Response()
                resp._content = b'{"results": []}'
                resp.headers = {"Content-Type": "application/json"}
                resp.status_code = 200
                if (self.fail_first and self.count == 1) or self.fail_all:
                    resp.status_code = 408
                return resp

        file = "test.txt.gz"
        out = TestBufferConanOutput()
        urls = [
            "http://localhost:{}/{}".format(8000 + i, file) for i in range(3)
        ]

        # Only the first file must be downloaded
        with tools.chdir(tools.mkdir_tmp()):
            requester = MockRequester()
            tools.get(urls,
                      requester=requester,
                      output=out,
                      retry=0,
                      retry_wait=0)
            self.assertEqual(1, requester.count)

        # Fail the first, download only the second
        with tools.chdir(tools.mkdir_tmp()):
            requester = MockRequester()
            requester.fail_first = True
            tools.get(urls,
                      requester=requester,
                      output=out,
                      retry=0,
                      retry_wait=0)
            self.assertEqual(2, requester.count)
            self.assertIn(
                "WARN: Could not download from the URL {}: Error 408 downloading file {}."
                " Trying another mirror.".format(urls[0], urls[0]), out)

        # Fail all downloads
        with tools.chdir(tools.mkdir_tmp()):
            requester = MockRequester()
            requester.fail_all = True
            with self.assertRaises(ConanException) as error:
                tools.get(urls,
                          requester=requester,
                          output=out,
                          retry=0,
                          retry_wait=0)
            self.assertEqual(3, requester.count)
            self.assertIn("All downloads from (3) URLs have failed.",
                          str(error.exception))
Ejemplo n.º 24
0
    def load_conan_txt_test(self):
        file_content = '''[requires]
OpenCV/2.4.10@phil/stable
OpenCV2/2.4.10@phil/stable
[build_requires]
MyPkg/1.0.0@phil/stable
[generators]
one
two
[imports]
OpenCV/bin, * -> ./bin # I need this binaries
OpenCV/lib, * -> ./lib
[options]
OpenCV:use_python=True
OpenCV:other_option=False
OpenCV2:use_python2=1
OpenCV2:other_option=Cosa
'''
        tmp_dir = temp_folder()
        file_path = os.path.join(tmp_dir, "file.txt")
        save(file_path, file_content)
        loader = ConanFileLoader(None, TestBufferConanOutput(), None)
        ret = loader.load_conanfile_txt(file_path, test_profile())
        options1 = OptionsValues.loads("""OpenCV:use_python=True
OpenCV:other_option=False
OpenCV2:use_python2=1
OpenCV2:other_option=Cosa""")
        requirements = Requirements()
        requirements.add("OpenCV/2.4.10@phil/stable")
        requirements.add("OpenCV2/2.4.10@phil/stable")
        build_requirements = ["MyPkg/1.0.0@phil/stable"]

        self.assertEqual(ret.requires, requirements)
        self.assertEqual(ret.build_requires, build_requirements)
        self.assertEqual(ret.generators, ["one", "two"])
        self.assertEqual(ret.options.values.dumps(), options1.dumps())

        ret.copy = Mock()
        ret.imports()

        self.assertTrue(ret.copy.call_args_list,
                        [('*', './bin', 'OpenCV/bin'),
                         ('*', './lib', 'OpenCV/lib')])

        # Now something that fails
        file_content = '''[requires]
OpenCV/2.4.104phil/stable
'''
        tmp_dir = temp_folder()
        file_path = os.path.join(tmp_dir, "file.txt")
        save(file_path, file_content)
        loader = ConanFileLoader(None, TestBufferConanOutput(), None)
        with six.assertRaisesRegex(self, ConanException,
                                   "The reference has too many '/'"):
            loader.load_conanfile_txt(file_path, test_profile())

        file_content = '''[requires]
OpenCV/2.4.10@phil/stable111111111111111111111111111111111111111111111111111111111111111
[imports]
OpenCV/bin/* - ./bin
'''
        tmp_dir = temp_folder()
        file_path = os.path.join(tmp_dir, "file.txt")
        save(file_path, file_content)
        loader = ConanFileLoader(None, TestBufferConanOutput(), None)
        with six.assertRaisesRegex(self, ConanException,
                                   "is too long. Valid names must contain"):
            loader.load_conanfile_txt(file_path, test_profile())
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
    def aux_cmake_test_setup_test(self):
        conanfile = ConanFile(TestBufferConanOutput(), None)
        conanfile.initialize(Settings({}), EnvValues())
        generator = CMakeGenerator(conanfile)
        aux_cmake_test_setup = generator.content

        # extract the conan_basic_setup macro
        macro = self._extract_macro("conan_basic_setup", aux_cmake_test_setup)
        self.assertEqual(
            """macro(conan_basic_setup)
    set(options TARGETS NO_OUTPUT_DIRS SKIP_RPATH KEEP_RPATHS SKIP_STD SKIP_FPIC)
    cmake_parse_arguments(ARGUMENTS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )

    if(CONAN_EXPORTED)
        conan_message(STATUS "Conan: called by CMake conan helper")
    endif()

    if(CONAN_IN_LOCAL_CACHE)
        conan_message(STATUS "Conan: called inside local cache")
    endif()

    if(NOT ARGUMENTS_NO_OUTPUT_DIRS)
        conan_message(STATUS "Conan: Adjusting output directories")
        conan_output_dirs_setup()
    endif()

    if(NOT ARGUMENTS_TARGETS)
        conan_message(STATUS "Conan: Using cmake global configuration")
        conan_global_flags()
    else()
        conan_message(STATUS "Conan: Using cmake targets configuration")
        conan_define_targets()
    endif()

    if(ARGUMENTS_SKIP_RPATH)
        # Change by "DEPRECATION" or "SEND_ERROR" when we are ready
        conan_message(WARNING "Conan: SKIP_RPATH is deprecated, it has been renamed to KEEP_RPATHS")
    endif()

    if(NOT ARGUMENTS_SKIP_RPATH AND NOT ARGUMENTS_KEEP_RPATHS)
        # Parameter has renamed, but we keep the compatibility with old SKIP_RPATH
        conan_set_rpath()
    endif()

    if(NOT ARGUMENTS_SKIP_STD)
        conan_set_std()
    endif()

    if(NOT ARGUMENTS_SKIP_FPIC)
        conan_set_fpic()
    endif()

    conan_check_compiler()
    conan_set_libcxx()
    conan_set_vs_runtime()
    conan_set_find_paths()
    conan_include_build_modules()
    conan_set_find_library_paths()
endmacro()""", macro)

        # extract the conan_set_find_paths macro
        macro = self._extract_macro("conan_set_find_paths",
                                    aux_cmake_test_setup)
        self.assertEqual(
            """macro(conan_set_find_paths)
    # CMAKE_MODULE_PATH does not have Debug/Release config, but there are variables
    # CONAN_CMAKE_MODULE_PATH_DEBUG to be used by the consumer
    # CMake can find findXXX.cmake files in the root of packages
    set(CMAKE_MODULE_PATH ${CONAN_CMAKE_MODULE_PATH} ${CMAKE_MODULE_PATH})

    # Make find_package() to work
    set(CMAKE_PREFIX_PATH ${CONAN_CMAKE_MODULE_PATH} ${CMAKE_PREFIX_PATH})

    # Set the find root path (cross build)
    set(CMAKE_FIND_ROOT_PATH ${CONAN_CMAKE_FIND_ROOT_PATH} ${CMAKE_FIND_ROOT_PATH})
    if(CONAN_CMAKE_FIND_ROOT_PATH_MODE_PROGRAM)
        set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ${CONAN_CMAKE_FIND_ROOT_PATH_MODE_PROGRAM})
    endif()
    if(CONAN_CMAKE_FIND_ROOT_PATH_MODE_LIBRARY)
        set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ${CONAN_CMAKE_FIND_ROOT_PATH_MODE_LIBRARY})
    endif()
    if(CONAN_CMAKE_FIND_ROOT_PATH_MODE_INCLUDE)
        set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ${CONAN_CMAKE_FIND_ROOT_PATH_MODE_INCLUDE})
    endif()
endmacro()""", macro)
Ejemplo n.º 27
0
    def valid_xml_test(self, use_toolset):
        tempdir = temp_folder()
        with chdir(tempdir):
            settings = Settings.loads(get_default_settings_yml())
            settings.os = "Windows"
            settings.compiler = "Visual Studio"
            settings.compiler.version = "11"
            settings.compiler.runtime = "MD"
            if use_toolset:
                settings.compiler.toolset = "v110"
            conanfile = ConanFile(TestBufferConanOutput(), None)
            conanfile.initialize(Settings({}), EnvValues())

            ref = ConanFileReference.loads("MyPkg/0.1@user/testing")
            cpp_info = CppInfo(ref.name, "dummy_root_folder1")
            conanfile.deps_cpp_info.add(ref.name, cpp_info)
            ref = ConanFileReference.loads("My.Fancy-Pkg_2/0.1@user/testing")
            cpp_info = CppInfo(ref.name, "dummy_root_folder2")
            conanfile.deps_cpp_info.add(ref.name, cpp_info)

            settings.arch = "x86"
            settings.build_type = "Debug"
            conanfile.settings = settings

            generator = VisualStudioMultiGenerator(conanfile)
            generator.output_path = ""
            content = generator.content

            self.assertEqual(2, len(content))
            self.assertIn('conanbuildinfo_multi.props', content.keys())
            self.assertIn('conanbuildinfo_debug_win32_v110.props',
                          content.keys())

            content_multi = content['conanbuildinfo_multi.props']
            self.assertIn(
                "<Import Condition=\"'$(Configuration)' == 'Debug' "
                "And '$(Platform)' == 'Win32' "
                "And '$(PlatformToolset)' == 'v110'\" "
                "Project=\"conanbuildinfo_debug_win32_v110.props\"/>",
                content_multi)

            with open('conanbuildinfo_multi.props', 'w') as f:
                f.write(content_multi)

            settings.arch = "x86_64"
            settings.build_type = "Release"
            settings.compiler.version = "15"
            settings.compiler.toolset = "v141"
            conanfile.settings = settings

            generator = VisualStudioMultiGenerator(conanfile)
            generator.output_path = ""
            content = generator.content

            self.assertEqual(2, len(content))
            self.assertIn('conanbuildinfo_multi.props', content.keys())
            self.assertIn('conanbuildinfo_release_x64_v141.props',
                          content.keys())

            content_multi = content['conanbuildinfo_multi.props']
            self.assertIn(
                "<Import Condition=\"'$(Configuration)' == 'Debug' "
                "And '$(Platform)' == 'Win32' "
                "And '$(PlatformToolset)' == 'v110'\" "
                "Project=\"conanbuildinfo_debug_win32_v110.props\"/>",
                content_multi)
            self.assertIn(
                "<Import Condition=\"'$(Configuration)' == 'Release' "
                "And '$(Platform)' == 'x64' "
                "And '$(PlatformToolset)' == 'v141'\" "
                "Project=\"conanbuildinfo_release_x64_v141.props\"/>",
                content_multi)

            os.unlink('conanbuildinfo_multi.props')
Ejemplo n.º 28
0
 def setUp(self):
     folder = temp_folder()
     self.cache = ClientCache(folder, output=TestBufferConanOutput())
     mkdir(self.cache.store)