Ejemplo n.º 1
0
 def test_existing_file(self):
     path = os.path.join(self.tmpdir, "keywords.py")
     touch(path)
     kwfile = KeywordFile(path)
     assert kwfile.filename == "keywords.py"
     assert kwfile.path == path
     assert kwfile.keywords == {}
Ejemplo n.º 2
0
 def test_fetch(self):
     project_config = BaseProjectConfig(UniversalConfig())
     with temporary_dir() as d:
         touch("cumulusci.yml")
         source = LocalFolderSource(project_config, {"path": d})
         project_config = source.fetch()
         assert project_config.repo_root == os.path.realpath(d)
Ejemplo n.º 3
0
    def test_get_api__skip_clean_meta_xml(self):
        with temporary_dir() as path:
            touch("package.xml")
            task = create_task(Deploy, {"path": path, "clean_meta_xml": False})

            api = task._get_api()
            zf = zipfile.ZipFile(io.BytesIO(base64.b64decode(api.package_zip)), "r")
            self.assertIn("package.xml", zf.namelist())
Ejemplo n.º 4
0
 def test_include_source__cached(self):
     global_config = BaseGlobalConfig()
     project_config = BaseProjectConfig(global_config)
     with temporary_dir() as d:
         touch("cumulusci.yml")
         other1 = project_config.include_source({"path": d})
         other2 = project_config.include_source({"path": d})
     assert other1 is other2
Ejemplo n.º 5
0
    def test_get_api__skip_clean_meta_xml(self):
        with temporary_dir() as path:
            touch("package.xml")
            task = create_task(Deploy, {"path": path, "clean_meta_xml": False})

            api = task._get_api()
            zf = zipfile.ZipFile(io.BytesIO(base64.b64decode(api.package_zip)),
                                 "r")
            self.assertIn("package.xml", zf.namelist())
Ejemplo n.º 6
0
 def test_parse_item_translates_namespace_tokens(self):
     with temporary_dir() as path:
         touch("___NAMESPACE___Foo__c.object")
         parser = MetadataFilenameParser("TestMDT",
                                         path,
                                         "object",
                                         delete=False)
         parser.parse_items()
     self.assertEqual(["%%%NAMESPACE%%%Foo__c"], parser.members)
Ejemplo n.º 7
0
 def test_convert_sfdx(self):
     with temporary_dir() as path:
         touch("README.md")  # make sure there's something in the directory
         with mock.patch(
                 "cumulusci.salesforce_api.package_zip.sfdx") as sfdx:
             builder = MetadataPackageZipBuilder()
             with builder._convert_sfdx_format(path, "Test Package"):
                 pass
     sfdx.assert_called_once()
Ejemplo n.º 8
0
 def test_get_flow__included_source(self):
     global_config = BaseGlobalConfig()
     with temporary_dir() as d:
         touch("cumulusci.yml")
         project_config = BaseProjectConfig(
             global_config, {"sources": {"test": {"path": d}}}
         )
         flow_config = project_config.get_flow("test:dev_org")
     assert flow_config.project_config is not project_config
     assert isinstance(flow_config.project_config.source, LocalFolderSource)
Ejemplo n.º 9
0
    def test_get_api__managed(self):
        with temporary_dir() as path:
            touch("package.xml")
            task = create_task(
                Deploy, {"path": path, "namespace_inject": "ns", "unmanaged": False}
            )

            api = task._get_api()
            zf = zipfile.ZipFile(io.BytesIO(base64.b64decode(api.package_zip)), "r")
            self.assertIn("package.xml", zf.namelist())
Ejemplo n.º 10
0
    def test_get_api__managed(self):
        with temporary_dir() as path:
            touch("package.xml")
            task = create_task(
                Deploy, {"path": path, "namespace_inject": "ns", "unmanaged": False}
            )

            api = task._get_api()
            zf = zipfile.ZipFile(io.BytesIO(base64.b64decode(api.package_zip)), "r")
            self.assertIn("package.xml", zf.namelist())
Ejemplo n.º 11
0
    def test_get_api__additional_options(self):
        with temporary_dir() as path:
            touch("package.xml")
            task = create_task(
                Deploy,
                {
                    "path": path,
                    "test_level": "RunSpecifiedTests",
                    "specified_tests": "TestA,TestB",
                    "unmanaged": False,
                },
            )

            api = task._get_api()
            assert api.run_tests == ["TestA", "TestB"]
            assert api.test_level == "RunSpecifiedTests"
Ejemplo n.º 12
0
    def test_parse_items__skips_files(self):
        with temporary_dir() as path:
            # create files that should be ignored by the parser
            for filename in (
                    ".hidden",
                    "CODEOWNERS",
                    "OWNERS",
                    "test.wrongext",
                    "test-meta.xml",
                    "Account.object",
                    "Custom__c.object",
            ):
                touch(filename)

            parser = BaseMetadataParser("TestMDT", path, "object", delete=True)
            parser.parse_item = mock.Mock()
            parser.parse_items()
            parser.parse_item.assert_called_once()
Ejemplo n.º 13
0
def test_project_config():
    universal_config = UniversalConfig()
    plan = mock.Mock()
    plan.version.product.repo_url = "https://github.com/SFDO-Tooling/CumulusCI-Test"

    with temporary_dir() as path:
        touch("cumulusci.yml")
        project_config = MetadeployProjectConfig(universal_config,
                                                 repo_root=path,
                                                 plan=plan)
        subproject_config = project_config.construct_subproject_config(
            repo_info={
                "root": path,
                "url": "https://github.com/SFDO-Tooling/CumulusCI-Test-Dep",
                "name": "CumulusCI-Test-Dep",
                "owner": "SFDO-Tooling",
                "commit": "abcdef",
            })

    assert subproject_config.plan is project_config.plan is plan
Ejemplo n.º 14
0
    def test_process_glob_list_arg(self):
        with temporary_dir():
            touch("foo.py")
            touch("bar.robot")

            # Expect passing arg as list works.
            self.assertEqual(
                ["foo.py", "bar.robot"],
                utils.process_glob_list_arg(["foo.py", "bar.robot"]),
            )

            # Falsy arg should return an empty list
            self.assertEqual([], utils.process_glob_list_arg(None))
            self.assertEqual([], utils.process_glob_list_arg(""))
            self.assertEqual([], utils.process_glob_list_arg([]))

            # Expect output to be in order given
            self.assertEqual(
                ["foo.py", "bar.robot"],
                utils.process_glob_list_arg("foo.py, bar.robot"),
            )

            # Expect sorted output of glob results
            self.assertEqual(["bar.robot", "foo.py"], utils.process_glob_list_arg("*"))

            # Patterns that don't match any files
            self.assertEqual(
                ["*.bar", "x.y.z"], utils.process_glob_list_arg("*.bar, x.y.z")
            )

            # Recursive
            os.mkdir("subdir")
            filename = os.path.join("subdir", "baz.resource")
            touch(filename)
            self.assertEqual([filename], utils.process_glob_list_arg("**/*.resource"))
Ejemplo n.º 15
0
def repo_root():
    with temporary_dir() as path:
        os.mkdir(".git")
        os.mkdir("src")
        pathlib.Path(path, "src", "package.xml").write_text(
            '<?xml version="1.0" encoding="utf-8"?>\n<Package xmlns="http://soap.sforce.com/2006/04/metadata"></Package>'
        )
        with open("cumulusci.yml", "w") as f:
            yaml.dump(
                {
                    "project": {
                        "dependencies": [
                            {
                                "name": "EDA unpackaged/pre/first",
                                "repo_owner": "SalesforceFoundation",
                                "repo_name": "EDA",
                                "subfolder": "unpackaged/pre/first",
                            },
                            {
                                "namespace":
                                "hed",
                                "version":
                                "1.99",
                                "dependencies": [{
                                    "namespace": "pub",
                                    "version": "1.5"
                                }],
                            },
                        ]
                    }
                },
                f,
            )
        pathlib.Path(path, "unpackaged", "pre", "first").mkdir(parents=True)
        touch(os.path.join("unpackaged", "pre", "first", "package.xml"))
        yield path
Ejemplo n.º 16
0
    def setUpClass(cls):
        # get_locator_module uses __file__ to locate the locator
        # module. We'll point it to a temporary directory so that
        # we can control what files we test against.

        cls.tempdir = Path(tempfile.mkdtemp())
        # sorted alphabetically, 5 should come after 40. The
        # code should be sorting numerically so that 5 comes
        # before 40. That's why "locators_5.py" is here.
        touch(Path(cls.tempdir, "locators_5.py"))
        touch(Path(cls.tempdir, "locators_39.py"))
        touch(Path(cls.tempdir, "locators_40.py"))

        dunder_file = Path(cls.tempdir, "utils.py").absolute()
        cls.patched_utils = mock.patch.object(robot_utils, "__file__",
                                              dunder_file)
        cls.patched_utils.start()
Ejemplo n.º 17
0
    def test_get_api__static_resources(self):
        with temporary_dir() as path:
            with open("package.xml", "w") as f:
                f.write("""<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <name>OtherType</name>
    </types>
</Package>""")
                touch("otherfile")

            with temporary_dir() as static_resource_path:
                os.mkdir("TestBundle")
                touch("TestBundle/test.txt")
                touch("TestBundle.resource-meta.xml")

                task = create_task(
                    Deploy,
                    {
                        "path": path,
                        "static_resource_path": static_resource_path,
                        "namespace_tokenize": "ns",
                        "namespace_inject": "ns",
                        "namespace_strip": "ns",
                        "unmanaged": True,
                    },
                )

                api = task._get_api()
                zf = zipfile.ZipFile(
                    io.BytesIO(base64.b64decode(api.package_zip)), "r")
                namelist = zf.namelist()
                self.assertIn("staticresources/TestBundle.resource", namelist)
                self.assertIn("staticresources/TestBundle.resource-meta.xml",
                              namelist)
                package_xml = zf.read("package.xml").decode()
                self.assertIn("<name>StaticResource</name>", package_xml)
                self.assertIn("<members>TestBundle</members>", package_xml)
Ejemplo n.º 18
0
    def test_get_api__static_resources(self):
        with temporary_dir() as path:
            with open("package.xml", "w") as f:
                f.write(
                    """<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <name>OtherType</name>
    </types>
</Package>"""
                )
                touch("otherfile")

            with temporary_dir() as static_resource_path:
                os.mkdir("TestBundle")
                touch("TestBundle/test.txt")
                touch("TestBundle.resource-meta.xml")

                task = create_task(
                    Deploy,
                    {
                        "path": path,
                        "static_resource_path": static_resource_path,
                        "namespace_tokenize": "ns",
                        "namespace_inject": "ns",
                        "namespace_strip": "ns",
                    },
                )

                api = task._get_api()
                zf = zipfile.ZipFile(io.BytesIO(base64.b64decode(api.package_zip)), "r")
                namelist = zf.namelist()
                self.assertIn("staticresources/TestBundle.resource", namelist)
                self.assertIn("staticresources/TestBundle.resource-meta.xml", namelist)
                package_xml = zf.read("package.xml").decode()
                self.assertIn("<name>StaticResource</name>", package_xml)
                self.assertIn("<members>TestBundle</members>", package_xml)
Ejemplo n.º 19
0
def retrieve_components(
    components,
    org_config,
    target: str,
    md_format: bool,
    extra_package_xml_opts: dict,
    namespace_tokenize: str,
    api_version: str,
):
    """Retrieve specified components from an org into a target folder.

    Retrieval is done using the sfdx force:source:retrieve command.

    Set `md_format` to True if retrieving into a folder with a package
    in metadata format. In this case the folder will be temporarily
    converted to dx format for the retrieval and then converted back.
    Retrievals to metadata format can also set `namespace_tokenize`
    to a namespace prefix to replace it with a `%%%NAMESPACE%%%` token.
    """

    with contextlib.ExitStack() as stack:
        if md_format:
            # Create target if it doesn't exist
            if not os.path.exists(target):
                os.mkdir(target)
                touch(os.path.join(target, "package.xml"))

            # Inject namespace
            if namespace_tokenize:
                process_text_in_directory(
                    target,
                    functools.partial(inject_namespace,
                                      namespace=namespace_tokenize,
                                      managed=True),
                )

            # Temporarily convert metadata format to DX format
            stack.enter_context(temporary_dir())
            os.mkdir("target")
            # We need to create sfdx-project.json
            # so that sfdx will recognize force-app as a package directory.
            with open("sfdx-project.json", "w") as f:
                json.dump(
                    {
                        "packageDirectories": [{
                            "path": "force-app",
                            "default": True
                        }]
                    }, f)
            sfdx(
                "force:mdapi:convert",
                log_note="Converting to DX format",
                args=["-r", target, "-d", "force-app"],
                check_return=True,
            )

        # Construct package.xml with components to retrieve, in its own tempdir
        package_xml_path = stack.enter_context(temporary_dir(chdir=False))
        _write_manifest(components, package_xml_path, api_version)

        # Retrieve specified components in DX format
        sfdx(
            "force:source:retrieve",
            access_token=org_config.access_token,
            log_note="Retrieving components",
            args=[
                "-a",
                str(api_version),
                "-x",
                os.path.join(package_xml_path, "package.xml"),
                "-w",
                "5",
            ],
            capture_output=False,
            check_return=True,
            env={"SFDX_INSTANCE_URL": org_config.instance_url},
        )

        if md_format:
            # Convert back to metadata format
            sfdx(
                "force:source:convert",
                log_note="Converting back to metadata format",
                args=["-r", "force-app", "-d", target],
                capture_output=False,
                check_return=True,
            )

            # Reinject namespace tokens
            if namespace_tokenize:
                process_text_in_directory(
                    target,
                    functools.partial(tokenize_namespace,
                                      namespace=namespace_tokenize),
                )

            # Regenerate package.xml,
            # to avoid reformatting or losing package name/scripts
            package_xml_opts = {
                "directory": target,
                "api_version": api_version,
                **extra_package_xml_opts,
            }
            package_xml = PackageXmlGenerator(**package_xml_opts)()
            with open(os.path.join(target, "package.xml"), "w") as f:
                f.write(package_xml)
Ejemplo n.º 20
0
    def test_builder(self):
        with temporary_dir() as path:

            # add package.xml
            with open(os.path.join(path, "package.xml"), "w") as f:
                f.write("""<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <version>45.0</version>
</Package>""")

            # add lwc
            lwc_path = os.path.join(path, "lwc")
            os.mkdir(lwc_path)

            # add lwc linting files (not included in zip)
            lwc_ignored_files = [".eslintrc.json", "jsconfig.json"]
            for lwc_ignored_file in lwc_ignored_files:
                touch(os.path.join(lwc_path, lwc_ignored_file))

            # add lwc component
            lwc_component_path = os.path.join(lwc_path, "myComponent")
            os.mkdir(lwc_component_path)

            # add lwc component files included in zip (in alphabetical order)
            lwc_component_files = [
                {
                    "name": "myComponent.html"
                },
                {
                    "name": "myComponent.js"
                },
                {
                    "name":
                    "myComponent.js-meta.xml",
                    "body:":
                    """<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="myComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>""",
                },
                {
                    "name": "myComponent.svg"
                },
                {
                    "name": "myComponent.css"
                },
            ]
            for lwc_component_file in lwc_component_files:
                with open(
                        os.path.join(lwc_component_path,
                                     lwc_component_file.get("name")),
                        "w",
                ) as f:
                    if lwc_component_file.get("body") is not None:
                        f.write(lwc_component_file.get("body"))

            # add lwc component files not included in zip
            for lwc_ignored_file in lwc_ignored_files:
                touch(os.path.join(lwc_component_path, lwc_ignored_file))

            # add lwc component sub-directory and files not included in zip
            lwc_component_test_path = os.path.join(lwc_component_path,
                                                   "__tests__")
            os.mkdir(lwc_component_test_path)
            touch(os.path.join(lwc_component_test_path, "test.js"))

            # add classes
            classes_path = os.path.join(path, "classes")
            os.mkdir(classes_path)
            class_files = [
                {
                    "name":
                    "MyClass.cls-meta.xml",
                    "body":
                    """<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <status>Active</status>
</ApexClass>
""",
                },
                {
                    "name": "MyClass.cls"
                },
            ]
            for class_file in class_files:
                with open(os.path.join(classes_path, class_file.get("name")),
                          "w") as f:
                    if class_file.get("body") is not None:
                        f.write(class_file.get("body"))

            # add objects
            objects_path = os.path.join(path, "objects")
            os.mkdir(objects_path)
            object_file_names = [
                "Account.object", "Contact.object", "CustomObject__c"
            ]
            object_file_names.sort()
            for object_file_name in object_file_names:
                touch(os.path.join(objects_path, object_file_name))

            # add sub-directory of objects (that doesn't really exist)
            objects_sub_path = os.path.join(objects_path,
                                            "does-not-exist-in-schema")
            os.mkdir(objects_sub_path)
            touch(os.path.join(objects_sub_path, "some.file"))

            # test
            builder = MetadataPackageZipBuilder(
                path=path,
                options={
                    "namespace_tokenize": "ns",
                    "namespace_inject": "ns",
                    "namespace_strip": "ns",
                },
            )

            # make sure result can be read as a zipfile
            result = builder.as_base64()
            zf = zipfile.ZipFile(io.BytesIO(base64.b64decode(result)), "r")
            assert set(zf.namelist()) == {
                "package.xml",
                "lwc/myComponent/myComponent.html",
                "lwc/myComponent/myComponent.js",
                "lwc/myComponent/myComponent.js-meta.xml",
                "lwc/myComponent/myComponent.svg",
                "lwc/myComponent/myComponent.css",
                "classes/MyClass.cls-meta.xml",
                "classes/MyClass.cls",
                "objects/Account.object",
                "objects/Contact.object",
                "objects/CustomObject__c",
                "objects/does-not-exist-in-schema/some.file",
            }
Ejemplo n.º 21
0
    def test_get_package_zip(self):
        with temporary_dir() as path:

            # add package.xml
            with open(os.path.join(path, "package.xml"), "w") as f:
                f.write(
                    """<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <version>45.0</version>
</Package>"""
                )

            # add lwc
            lwc_path = os.path.join(path, "lwc")
            os.mkdir(lwc_path)

            # add lwc linting files (not included in zip)
            lwc_ignored_files = [".eslintrc.json", "jsconfig.json"]
            for lwc_ignored_file in lwc_ignored_files:
                touch(os.path.join(lwc_path, lwc_ignored_file))

            # add lwc component
            lwc_component_path = os.path.join(lwc_path, "myComponent")
            os.mkdir(lwc_component_path)

            # add lwc component files included in zip (in alphabetical order)
            lwc_component_files = [
                {"name": "myComponent.html"},
                {"name": "myComponent.js"},
                {
                    "name": "myComponent.js-meta.xml",
                    "body:": """<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="myComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>""",
                },
                {"name": "myComponent.svg"},
                {"name": "myComponent.css"},
            ]
            for lwc_component_file in lwc_component_files:
                with open(
                    os.path.join(lwc_component_path, lwc_component_file.get("name")),
                    "w",
                ) as f:
                    if lwc_component_file.get("body") is not None:
                        f.write(lwc_component_file.get("body"))

            # add lwc component files not included in zip
            for lwc_ignored_file in lwc_ignored_files:
                touch(os.path.join(lwc_component_path, lwc_ignored_file))

            # add lwc component sub-directory and files not included in zip
            lwc_component_test_path = os.path.join(lwc_component_path, "__tests__")
            os.mkdir(lwc_component_test_path)
            touch(os.path.join(lwc_component_test_path, "test.js"))

            # add classes
            classes_path = os.path.join(path, "classes")
            os.mkdir(classes_path)
            class_files = [
                {
                    "name": "MyClass.cls-meta.xml",
                    "body": """<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <status>Active</status>
</ApexClass>
""",
                },
                {"name": "MyClass.cls"},
            ]
            for class_file in class_files:
                with open(os.path.join(classes_path, class_file.get("name")), "w") as f:
                    if class_file.get("body") is not None:
                        f.write(class_file.get("body"))

            # add objects
            objects_path = os.path.join(path, "objects")
            os.mkdir(objects_path)
            object_file_names = ["Account.object", "Contact.object", "CustomObject__c"]
            object_file_names.sort()
            for object_file_name in object_file_names:
                touch(os.path.join(objects_path, object_file_name))

            # add sub-directory of objects (that doesn't really exist)
            objects_sub_path = os.path.join(objects_path, "does-not-exist-in-schema")
            os.mkdir(objects_sub_path)
            touch(os.path.join(objects_sub_path, "some.file"))

            # test
            task = create_task(
                Deploy,
                {
                    "path": path,
                    "namespace_tokenize": "ns",
                    "namespace_inject": "ns",
                    "namespace_strip": "ns",
                },
            )

            zip_bytes = io.BytesIO()
            zipf = zipfile.ZipFile(zip_bytes, "w", zipfile.ZIP_DEFLATED)

            with cd(path):
                for file_to_package in task._get_files_to_package():
                    zipf.write(file_to_package)
                zipf.close()

            zipf_processed = task._process_zip_file(zipfile.ZipFile(zip_bytes))
            fp = zipf_processed.fp
            zipf_processed.close()
            expected = bytes_to_native_str(base64.b64encode(fp.getvalue()))

            actual = task._get_package_zip(path)

            self.assertEqual(expected, actual)
Ejemplo n.º 22
0
    def test_get_package_zip(self):
        with temporary_dir() as path:

            # add package.xml
            with open(os.path.join(path, "package.xml"), "w") as f:
                f.write("""<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <version>45.0</version>
</Package>""")

            # add lwc
            lwc_path = os.path.join(path, "lwc")
            os.mkdir(lwc_path)

            # add lwc linting files (not included in zip)
            lwc_ignored_files = [".eslintrc.json", "jsconfig.json"]
            for lwc_ignored_file in lwc_ignored_files:
                touch(os.path.join(lwc_path, lwc_ignored_file))

            # add lwc component
            lwc_component_path = os.path.join(lwc_path, "myComponent")
            os.mkdir(lwc_component_path)

            # add lwc component files included in zip (in alphabetical order)
            lwc_component_files = [
                {
                    "name": "myComponent.html"
                },
                {
                    "name": "myComponent.js"
                },
                {
                    "name":
                    "myComponent.js-meta.xml",
                    "body:":
                    """<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="myComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>""",
                },
                {
                    "name": "myComponent.svg"
                },
                {
                    "name": "myComponent.css"
                },
            ]
            for lwc_component_file in lwc_component_files:
                with open(
                        os.path.join(lwc_component_path,
                                     lwc_component_file.get("name")),
                        "w",
                ) as f:
                    if lwc_component_file.get("body") is not None:
                        f.write(lwc_component_file.get("body"))

            # add lwc component files not included in zip
            for lwc_ignored_file in lwc_ignored_files:
                touch(os.path.join(lwc_component_path, lwc_ignored_file))

            # add lwc component sub-directory and files not included in zip
            lwc_component_test_path = os.path.join(lwc_component_path,
                                                   "__tests__")
            os.mkdir(lwc_component_test_path)
            touch(os.path.join(lwc_component_test_path, "test.js"))

            # add classes
            classes_path = os.path.join(path, "classes")
            os.mkdir(classes_path)
            class_files = [
                {
                    "name":
                    "MyClass.cls-meta.xml",
                    "body":
                    """<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <status>Active</status>
</ApexClass>
""",
                },
                {
                    "name": "MyClass.cls"
                },
            ]
            for class_file in class_files:
                with open(os.path.join(classes_path, class_file.get("name")),
                          "w") as f:
                    if class_file.get("body") is not None:
                        f.write(class_file.get("body"))

            # add objects
            objects_path = os.path.join(path, "objects")
            os.mkdir(objects_path)
            object_file_names = [
                "Account.object", "Contact.object", "CustomObject__c"
            ]
            object_file_names.sort()
            for object_file_name in object_file_names:
                touch(os.path.join(objects_path, object_file_name))

            # add sub-directory of objects (that doesn't really exist)
            objects_sub_path = os.path.join(objects_path,
                                            "does-not-exist-in-schema")
            os.mkdir(objects_sub_path)
            touch(os.path.join(objects_sub_path, "some.file"))

            # test
            task = create_task(
                Deploy,
                {
                    "path": path,
                    "namespace_tokenize": "ns",
                    "namespace_inject": "ns",
                    "namespace_strip": "ns",
                },
            )

            zip_bytes = io.BytesIO()
            zipf = zipfile.ZipFile(zip_bytes, "w", zipfile.ZIP_DEFLATED)

            with cd(path):
                for file_to_package in task._get_files_to_package():
                    zipf.write(file_to_package)
                zipf.close()

            zipf_processed = task._process_zip_file(zipfile.ZipFile(zip_bytes))
            fp = zipf_processed.fp
            zipf_processed.close()
            expected = base64.b64encode(fp.getvalue()).decode("utf-8")

            actual = task._get_package_zip(path)

            self.assertEqual(expected, actual)
Ejemplo n.º 23
0
    def test_add_files_to_package(self):
        with temporary_dir() as path:
            expected = []

            # add package.xml
            with open(os.path.join(path, "package.xml"), "w") as f:
                f.write("""<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <version>45.0</version>
</Package>""")
                expected.append("package.xml")

            # add lwc
            lwc_path = os.path.join(path, "lwc")
            os.mkdir(lwc_path)

            # add lwc linting files (not included in zip)
            lwc_ignored_files = [".eslintrc.json", "jsconfig.json"]
            for lwc_ignored_file in lwc_ignored_files:
                touch(os.path.join(lwc_path, lwc_ignored_file))

            # add lwc component
            lwc_component_path = os.path.join(lwc_path, "myComponent")
            os.mkdir(lwc_component_path)

            # add lwc component files included in zip (in alphabetical order)
            lwc_component_files = [
                {
                    "name": "myComponent.html"
                },
                {
                    "name": "myComponent.js"
                },
                {
                    "name":
                    "myComponent.js-meta.xml",
                    "body:":
                    """<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="myComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>""",
                },
                {
                    "name": "myComponent.svg"
                },
                {
                    "name": "myComponent.css"
                },
            ]
            for lwc_component_file in lwc_component_files:
                with open(
                        os.path.join(lwc_component_path,
                                     lwc_component_file.get("name")),
                        "w",
                ) as f:
                    if lwc_component_file.get("body") is not None:
                        f.write(lwc_component_file.get("body"))
                    expected.append(
                        f"lwc/myComponent/{lwc_component_file.get('name')}")

            # add lwc component files not included in zip
            for lwc_ignored_file in lwc_ignored_files:
                touch(os.path.join(lwc_component_path, lwc_ignored_file))

            # add lwc component sub-directory and files not included in zip
            lwc_component_test_path = os.path.join(lwc_component_path,
                                                   "__tests__")
            os.mkdir(lwc_component_test_path)
            touch(os.path.join(lwc_component_test_path, "test.js"))

            # add classes
            classes_path = os.path.join(path, "classes")
            os.mkdir(classes_path)
            class_files = [
                {
                    "name":
                    "MyClass.cls-meta.xml",
                    "body":
                    """<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <status>Active</status>
</ApexClass>
""",
                },
                {
                    "name": "MyClass.cls"
                },
            ]
            for class_file in class_files:
                with open(os.path.join(classes_path, class_file.get("name")),
                          "w") as f:
                    if class_file.get("body") is not None:
                        f.write(class_file.get("body"))
                    expected.append(f"classes/{class_file.get('name')}")

            # add objects
            objects_path = os.path.join(path, "objects")
            os.mkdir(objects_path)
            object_file_names = [
                "Account.object", "Contact.object", "CustomObject__c"
            ]
            object_file_names.sort()
            for object_file_name in object_file_names:
                with open(os.path.join(objects_path, object_file_name), "w"):
                    expected.append(f"objects/{object_file_name}")

            # add sub-directory of objects (that doesn't really exist)
            objects_sub_path = os.path.join(objects_path,
                                            "does-not-exist-in-schema")
            os.mkdir(objects_sub_path)
            with open(os.path.join(objects_sub_path, "some.file"), "w"):
                expected.append("objects/does-not-exist-in-schema/some.file")

            # test
            builder = MetadataPackageZipBuilder()

            expected_set = set(expected)
            builder._add_files_to_package(path)
            actual_set = set(builder.zf.namelist())
            assert expected_set == actual_set