From 9db1001a4b03ecfe402cde31f42ca943647930de Mon Sep 17 00:00:00 2001 From: Jesus Orosco Date: Thu, 9 Apr 2026 12:53:36 -0700 Subject: [PATCH 1/8] adding some new tests that defines the contract between sf cli and python cli --- tests/test_sf_cli_contract.py | 300 ++++++++++++++++++++++++++++++++++ 1 file changed, 300 insertions(+) create mode 100644 tests/test_sf_cli_contract.py diff --git a/tests/test_sf_cli_contract.py b/tests/test_sf_cli_contract.py new file mode 100644 index 0000000..e60f68f --- /dev/null +++ b/tests/test_sf_cli_contract.py @@ -0,0 +1,300 @@ +""" +Contract tests: verify that the Python CLI accepts exactly the argument signatures +passed by the SF CLI plugin (@salesforce/plugin-data-code-extension v0.1.4) via spawn(). + +These tests do NOT exercise business logic. They verify that: + 1. All flags recognised by the SF CLI plugin are still accepted by the Python CLI. + 2. Exit code is never 2 (Click's "bad usage" code) for valid SF CLI invocations. + 3. stdout patterns parsed by the SF CLI plugin are present in the Python CLI output. + +Source of truth for expected args and stdout regex patterns: + data-code-extension/src/utils/datacodeBinaryExecutor.ts +""" + +import os +import re +from typing import ClassVar +from unittest.mock import patch + +from click.testing import CliRunner + +from datacustomcode.cli import ( + deploy, + init, + run, + scan, + zip as zip_cmd, +) +from datacustomcode.deploy import AccessTokenResponse + + +class TestInitArgContract: + """ + SF CLI spawn: datacustomcode init --code-type + Ref: executeBinaryInit() + """ + + @patch("datacustomcode.template.copy_script_template") + @patch("datacustomcode.scan.dc_config_json_from_file") + @patch("datacustomcode.scan.update_config") + @patch("datacustomcode.scan.write_sdk_config") + def test_accepts_code_type_script( + self, mock_write_sdk, mock_update, mock_scan, mock_copy + ): + mock_scan.return_value = {} + mock_update.return_value = {} + runner = CliRunner() + with runner.isolated_filesystem(): + os.makedirs(os.path.join("mydir", "payload"), exist_ok=True) + result = runner.invoke(init, ["--code-type", "script", "mydir"]) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.template.copy_function_template") + @patch("datacustomcode.scan.dc_config_json_from_file") + @patch("datacustomcode.scan.update_config") + @patch("datacustomcode.scan.write_sdk_config") + def test_accepts_code_type_function( + self, mock_write_sdk, mock_update, mock_scan, mock_copy + ): + mock_scan.return_value = {} + mock_update.return_value = {} + runner = CliRunner() + with runner.isolated_filesystem(): + os.makedirs(os.path.join("mydir", "payload"), exist_ok=True) + result = runner.invoke(init, ["--code-type", "function", "mydir"]) + assert result.exit_code != 2, result.output + + +class TestScanArgContract: + """ + SF CLI spawn: datacustomcode scan [--dry-run] [--no-requirements] + [--config ] + Ref: executeBinaryScan() + """ + + @patch("datacustomcode.scan.update_config") + def test_accepts_positional_entrypoint(self, mock_update): + mock_update.return_value = {} + runner = CliRunner() + result = runner.invoke(scan, ["--dry-run", "payload/entrypoint.py"]) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.scan.update_config") + def test_accepts_dry_run_flag(self, mock_update): + mock_update.return_value = {} + runner = CliRunner() + result = runner.invoke(scan, ["--dry-run", "payload/entrypoint.py"]) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.scan.update_config") + def test_accepts_no_requirements_flag(self, mock_update): + mock_update.return_value = {} + runner = CliRunner() + result = runner.invoke( + scan, ["--no-requirements", "--dry-run", "payload/entrypoint.py"] + ) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.scan.update_config") + def test_accepts_config_flag(self, mock_update): + mock_update.return_value = {} + runner = CliRunner() + result = runner.invoke( + scan, + ["--config", "custom/config.json", "--dry-run", "payload/entrypoint.py"], + ) + assert result.exit_code != 2, result.output + + +class TestZipArgContract: + """ + SF CLI spawn: datacustomcode zip [--network ] + Ref: executeBinaryZip() + """ + + @patch("datacustomcode.deploy.zip") + @patch("datacustomcode.scan.find_base_directory") + @patch("datacustomcode.scan.get_package_type") + def test_accepts_positional_packagedir( + self, mock_pkg_type, mock_find_base, mock_zip + ): + mock_find_base.return_value = "payload" + mock_pkg_type.return_value = "script" + runner = CliRunner() + result = runner.invoke(zip_cmd, ["payload"]) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.deploy.zip") + @patch("datacustomcode.scan.find_base_directory") + @patch("datacustomcode.scan.get_package_type") + def test_accepts_network_flag(self, mock_pkg_type, mock_find_base, mock_zip): + mock_find_base.return_value = "payload" + mock_pkg_type.return_value = "script" + runner = CliRunner() + result = runner.invoke(zip_cmd, ["--network", "custom", "payload"]) + assert result.exit_code != 2, result.output + + +class TestDeployArgContract: + """ + SF CLI spawn: + datacustomcode deploy + --name --version --description + --path --sf-cli-org --cpu-size + [--network ] [--function-invoke-opt ] + Ref: executeBinaryDeploy() + """ + + _BASE_ARGS: ClassVar[list[str]] = [ + "--name", "my-pkg", + "--version", "1.0.0", + "--description", "My description", + "--path", "payload", + "--sf-cli-org", "my-org", + "--cpu-size", "CPU_2XL", + ] # fmt: skip + + @patch("datacustomcode.deploy._retrieve_access_token_from_sf_cli") + @patch("datacustomcode.deploy.deploy_full") + @patch("datacustomcode.cli.find_base_directory") + @patch("datacustomcode.cli.get_package_type") + def test_accepts_required_flags( + self, mock_pkg_type, mock_find_base, mock_deploy_full, mock_sf_cli_token + ): + mock_find_base.return_value = "payload" + mock_pkg_type.return_value = "script" + mock_sf_cli_token.return_value = AccessTokenResponse( + access_token="tok", instance_url="https://example.com" + ) + runner = CliRunner() + result = runner.invoke(deploy, self._BASE_ARGS) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.deploy._retrieve_access_token_from_sf_cli") + @patch("datacustomcode.deploy.deploy_full") + @patch("datacustomcode.cli.find_base_directory") + @patch("datacustomcode.cli.get_package_type") + def test_accepts_network_flag( + self, mock_pkg_type, mock_find_base, mock_deploy_full, mock_sf_cli_token + ): + mock_find_base.return_value = "payload" + mock_pkg_type.return_value = "script" + mock_sf_cli_token.return_value = AccessTokenResponse( + access_token="tok", instance_url="https://example.com" + ) + runner = CliRunner() + result = runner.invoke(deploy, [*self._BASE_ARGS, "--network", "custom"]) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.deploy._retrieve_access_token_from_sf_cli") + @patch("datacustomcode.deploy.deploy_full") + @patch("datacustomcode.cli.find_base_directory") + @patch("datacustomcode.cli.get_package_type") + def test_accepts_function_invoke_opt_flag( + self, mock_pkg_type, mock_find_base, mock_deploy_full, mock_sf_cli_token + ): + mock_find_base.return_value = "payload" + mock_pkg_type.return_value = "function" + mock_sf_cli_token.return_value = AccessTokenResponse( + access_token="tok", instance_url="https://example.com" + ) + runner = CliRunner() + result = runner.invoke( + deploy, [*self._BASE_ARGS, "--function-invoke-opt", "ASYNC"] + ) + assert result.exit_code != 2, result.output + + +class TestRunArgContract: + """ + SF CLI spawn: + datacustomcode run --sf-cli-org + [--config-file ] [--dependencies ] + Ref: executeBinaryRun() + + Known incompatibility: SF CLI passes `--dependencies` once as a single string. + Python CLI declares multiple=True, so the value arrives as a 1-tuple containing + the raw string rather than individual dep names. + """ + + @patch("datacustomcode.run.run_entrypoint") + def test_accepts_sf_cli_org_and_positional(self, mock_run): + runner = CliRunner() + result = runner.invoke(run, ["--sf-cli-org", "my-org", "payload/entrypoint.py"]) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.run.run_entrypoint") + def test_accepts_config_file_flag(self, mock_run): + runner = CliRunner() + result = runner.invoke( + run, + [ + "--sf-cli-org", + "my-org", + "--config-file", + "payload/config.json", + "payload/entrypoint.py", + ], + ) + assert result.exit_code != 2, result.output + + @patch("datacustomcode.run.run_entrypoint") + def test_accepts_dependencies_as_single_string(self, mock_run): + """SF CLI passes --dependencies once as a comma-separated string. + + Python CLI uses multiple=True, so run_entrypoint receives ("dep1,dep2",) + not ("dep1", "dep2"). The string is NOT split on commas. + """ + runner = CliRunner() + result = runner.invoke( + run, + [ + "--sf-cli-org", + "my-org", + "--dependencies", + "dep1,dep2", + "payload/entrypoint.py", + ], + ) + assert result.exit_code != 2, result.output + # Document the incompatibility: SF CLI passes a single "dep1,dep2" string, + # but run_entrypoint receives ("dep1,dep2",) — not ("dep1", "dep2"). + assert mock_run.call_args[0][2] == ("dep1,dep2",) + + +class TestSfCliOutputRegexContract: + """ + The SF CLI plugin parses stdout from each command with regex patterns. + These tests verify that the Python CLI's actual output matches what the + plugin expects (v0.1.4). + + Ref: stdout parsing in each executeBinary*() method of datacodeBinaryExecutor.ts. + """ + + # ── init ────────────────────────────────────────────────────────────────── + + @patch("datacustomcode.template.copy_script_template") + @patch("datacustomcode.scan.dc_config_json_from_file") + @patch("datacustomcode.scan.update_config") + @patch("datacustomcode.scan.write_sdk_config") + def test_init_copying_template_pattern( + self, mock_write_sdk, mock_update, mock_scan, mock_copy + ): + """SF CLI parses 'Copying template to ' from init stdout.""" + mock_scan.return_value = {} + mock_update.return_value = {} + runner = CliRunner() + with runner.isolated_filesystem(): + os.makedirs(os.path.join("mydir", "payload"), exist_ok=True) + result = runner.invoke(init, ["--code-type", "script", "mydir"]) + assert re.search(r"Copying template to .+", result.output) + + # ── scan ────────────────────────────────────────────────────────────────── + + @patch("datacustomcode.scan.update_config") + def test_scan_scanning_file_pattern(self, mock_update): + """SF CLI parses 'Scanning ...' from scan stdout.""" + mock_update.return_value = {} + runner = CliRunner() + result = runner.invoke(scan, ["--dry-run", "payload/entrypoint.py"]) + assert re.search(r"Scanning .+\.\.\.", result.output) From 26746b7f103d9bd769ec0b9fd5648badc6ccffae Mon Sep 17 00:00:00 2001 From: Jesus Orosco Date: Thu, 9 Apr 2026 15:16:29 -0700 Subject: [PATCH 2/8] add an integration workflow that tests real sf cli against python cli --- .github/workflows/sf_cli_integration.yml | 172 +++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 .github/workflows/sf_cli_integration.yml diff --git a/.github/workflows/sf_cli_integration.yml b/.github/workflows/sf_cli_integration.yml new file mode 100644 index 0000000..1a77c42 --- /dev/null +++ b/.github/workflows/sf_cli_integration.yml @@ -0,0 +1,172 @@ +name: SF CLI Integration Test + +on: + pull_request: + +jobs: + sf-cli-integration: + runs-on: ubuntu-latest + env: + SF_AUTOUPDATE_DISABLE: true + NO_COLOR: '1' + + steps: + # ── Setup ───────────────────────────────────────────────────────────────── + + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python 3.11 + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install Poetry and Python SDK + run: | + python -m pip install --upgrade pip + pip install poetry + make develop + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: lts/* + + - name: Install Salesforce CLI + run: npm install -g @salesforce/cli + + - name: Install data-code-extension plugin + run: sf plugins install @salesforce/plugin-data-code-extension --force + + # ── Script: init ────────────────────────────────────────────────────────── + + - name: '[script] init — sf data-code-extension script init --package-dir testScript' + run: | + sf data-code-extension script init --package-dir testScript || { + echo "::error::sf data-code-extension script init FAILED. Verify --package-dir is still a recognised flag and that the command exits 0 on success." + exit 1 + } + + - name: '[script] verify init — expected files exist' + run: | + test -f testScript/payload/entrypoint.py || { + echo "::error::testScript/payload/entrypoint.py not found after init. The init command may not have copied the script template." + exit 1 + } + test -f testScript/.datacustomcode_proj/sdk_config.json || { + echo "::error::testScript/.datacustomcode_proj/sdk_config.json not found after init. The SDK config marker was not written." + exit 1 + } + + # ── Script: scan ────────────────────────────────────────────────────────── + + - name: '[script] scan — sf data-code-extension script scan --entrypoint testScript/payload/entrypoint.py' + run: | + sf data-code-extension script scan --entrypoint testScript/payload/entrypoint.py || { + echo "::error::sf data-code-extension script scan FAILED. Verify --entrypoint is still a recognised flag and the command exits 0." + exit 1 + } + + - name: '[script] verify scan — config.json contains permissions' + run: | + python - <<'EOF' + import json, sys + path = "testScript/payload/config.json" + try: + with open(path) as f: + data = json.load(f) + except Exception as e: + print(f"::error::Could not read {path}: {e}") + sys.exit(1) + if "permissions" not in data: + print(f"::error::{path} is missing 'permissions' key after scan. Got: {json.dumps(data)}") + sys.exit(1) + print("config.json OK:", json.dumps(data, indent=2)) + EOF + + # ── Script: zip ─────────────────────────────────────────────────────────── + + - name: '[script] prepare for zip — clear requirements.txt to skip native-dep Docker build' + run: echo "" > testScript/payload/requirements.txt + + - name: '[script] zip — sf data-code-extension script zip --package-dir testScript' + run: | + sf data-code-extension script zip --package-dir testScript || { + echo "::error::sf data-code-extension script zip FAILED. Verify --package-dir is still recognised and the command exits 0." + exit 1 + } + + - name: '[script] verify zip — deployment.zip exists' + run: | + test -f deployment.zip || { + echo "::error::deployment.zip not found after sf data-code-extension script zip. The zip command may have written to a different path or failed silently." + exit 1 + } + + # ── Function: init ──────────────────────────────────────────────────────── + + - name: '[function] init — sf data-code-extension function init --package-dir testFunction' + run: | + sf data-code-extension function init --package-dir testFunction || { + echo "::error::sf data-code-extension function init FAILED. Verify --package-dir is still recognised and the function template copies correctly." + exit 1 + } + + - name: '[function] verify init — expected files exist' + run: | + test -f testFunction/payload/entrypoint.py || { + echo "::error::testFunction/payload/entrypoint.py not found after function init." + exit 1 + } + test -f testFunction/.datacustomcode_proj/sdk_config.json || { + echo "::error::testFunction/.datacustomcode_proj/sdk_config.json not found after function init." + exit 1 + } + + # ── Function: scan ──────────────────────────────────────────────────────── + + - name: '[function] scan — sf data-code-extension function scan --entrypoint testFunction/payload/entrypoint.py' + run: | + sf data-code-extension function scan --entrypoint testFunction/payload/entrypoint.py || { + echo "::error::sf data-code-extension function scan FAILED." + exit 1 + } + + - name: '[function] verify scan — config.json contains entryPoint' + run: | + python - <<'EOF' + import json, sys + path = "testFunction/payload/config.json" + try: + with open(path) as f: + data = json.load(f) + except Exception as e: + print(f"::error::Could not read {path}: {e}") + sys.exit(1) + if "entryPoint" not in data: + print(f"::error::{path} is missing 'entryPoint' key after scan. Got: {json.dumps(data)}") + sys.exit(1) + print("config.json OK:", json.dumps(data, indent=2)) + EOF + + # ── Function: zip ───────────────────────────────────────────────────────── + + - name: '[function] prepare for zip — clear requirements.txt to skip native-dep Docker build' + run: echo "" > testFunction/payload/requirements.txt + + - name: '[function] clean up previous deployment.zip before function zip' + run: rm -f deployment.zip + + - name: '[function] zip — sf data-code-extension function zip --package-dir testFunction' + run: | + sf data-code-extension function zip --package-dir testFunction || { + echo "::error::sf data-code-extension function zip FAILED." + exit 1 + } + + - name: '[function] verify zip — deployment.zip exists' + run: | + test -f deployment.zip || { + echo "::error::deployment.zip not found after sf data-code-extension function zip." + exit 1 + } From 0eea072890f11809f3c1ab81c8c2200c3df7b57f Mon Sep 17 00:00:00 2001 From: Jesus Orosco Date: Thu, 9 Apr 2026 15:26:53 -0700 Subject: [PATCH 3/8] add to path --- .github/workflows/sf_cli_integration.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/sf_cli_integration.yml b/.github/workflows/sf_cli_integration.yml index 1a77c42..75ed67f 100644 --- a/.github/workflows/sf_cli_integration.yml +++ b/.github/workflows/sf_cli_integration.yml @@ -27,6 +27,9 @@ jobs: pip install poetry make develop + - name: Add Poetry venv to PATH + run: echo "$(poetry env info --path)/bin" >> $GITHUB_PATH + - name: Set up Node.js uses: actions/setup-node@v4 with: From 218b13852e8282b0c1e9ca6a9176a0b66385c294 Mon Sep 17 00:00:00 2001 From: Jesus Orosco Date: Thu, 9 Apr 2026 15:52:05 -0700 Subject: [PATCH 4/8] testing out run command --- .github/workflows/sf_cli_integration.yml | 44 +++++++++ scripts/mock_sf_server.py | 113 +++++++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 scripts/mock_sf_server.py diff --git a/.github/workflows/sf_cli_integration.yml b/.github/workflows/sf_cli_integration.yml index 75ed67f..87d274f 100644 --- a/.github/workflows/sf_cli_integration.yml +++ b/.github/workflows/sf_cli_integration.yml @@ -41,6 +41,28 @@ jobs: - name: Install data-code-extension plugin run: sf plugins install @salesforce/plugin-data-code-extension --force + - name: Set up Java 17 (required for PySpark during run) + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + # ── Mock Salesforce server + fake org auth ──────────────────────────────── + + - name: Start mock Salesforce server + run: python scripts/mock_sf_server.py & + env: + MOCK_SF_PORT: '8888' + + - name: Register fake org 'dev1' with SF CLI + run: | + sleep 1 + echo "fake_access_token_00D000000000001AAA" | \ + sf org login access-token \ + --instance-url http://localhost:8888 \ + --alias dev1 \ + --no-prompt + # ── Script: init ────────────────────────────────────────────────────────── - name: '[script] init — sf data-code-extension script init --package-dir testScript' @@ -106,6 +128,17 @@ jobs: exit 1 } + # ── Script: run ─────────────────────────────────────────────────────────── + + - name: '[script] run — sf data-code-extension script run --entrypoint testScript/payload/entrypoint.py -o dev1' + run: | + sf data-code-extension script run \ + --entrypoint testScript/payload/entrypoint.py \ + -o dev1 || { + echo "::error::sf data-code-extension script run FAILED. Check mock server output above for which endpoint failed. The --entrypoint flag or SF CLI org auth contract may have changed." + exit 1 + } + # ── Function: init ──────────────────────────────────────────────────────── - name: '[function] init — sf data-code-extension function init --package-dir testFunction' @@ -173,3 +206,14 @@ jobs: echo "::error::deployment.zip not found after sf data-code-extension function zip." exit 1 } + + # ── Function: run ───────────────────────────────────────────────────────── + + - name: '[function] run — sf data-code-extension function run --entrypoint testFunction/payload/entrypoint.py -o dev1' + run: | + sf data-code-extension function run \ + --entrypoint testFunction/payload/entrypoint.py \ + -o dev1 || { + echo "::error::sf data-code-extension function run FAILED. Check mock server output above; the --entrypoint flag or SF CLI org auth contract may have changed." + exit 1 + } diff --git a/scripts/mock_sf_server.py b/scripts/mock_sf_server.py new file mode 100644 index 0000000..81fb404 --- /dev/null +++ b/scripts/mock_sf_server.py @@ -0,0 +1,113 @@ +"""Minimal mock Salesforce server for CI integration tests. + +Intercepts the HTTP calls made during ``sf data-code-extension script|function run`` +so that neither a real Salesforce org nor real Data Cloud data is required. + +Endpoints handled +----------------- +GET /services/oauth2/userinfo + Called by ``sf org login access-token`` to resolve a username from a token, + and by ``connection.refreshAuth()`` in the SF CLI plugin. + +POST /services/oauth2/token + Called by ``connection.refreshAuth()`` when it tries to exchange a token. + +POST /services/data/v66.0/ssot/query-sql + Called by SFCLIDataCloudReader when the script entrypoint reads a DLO/DMO. + Returns fake rows with the columns expected by the default script template + (Account_std__dll: description__c, sfdcorganizationid__c, kq_id__c). + +GET /* (catch-all) + Returns {"status": "ok"} for any other SF API path the CLI may probe. + +Usage +----- + python scripts/mock_sf_server.py # listens on port 8888 + MOCK_SF_PORT=9000 python scripts/mock_sf_server.py + python scripts/mock_sf_server.py 9000 +""" + +from __future__ import annotations + +from http.server import BaseHTTPRequestHandler, HTTPServer +import json +import os +import sys + +PORT = ( + int(sys.argv[1]) + if len(sys.argv) > 1 + else int(os.environ.get("MOCK_SF_PORT", "8888")) +) + +_USERINFO = { + "sub": "https://test.salesforce.com/id/00D000000000001AAA/005000000000001AAA", + "user_id": "005000000000001AAA", + "organization_id": "00D000000000001AAA", + "preferred_username": "dev1@example.com", + "name": "Dev User", + "email": "dev1@example.com", + "username": "dev1@example.com", + "active": True, +} + +_TOKEN_RESPONSE = { + "access_token": "fake_access_token_00D000000000001AAA", + "instance_url": f"http://localhost:{PORT}", + "token_type": "Bearer", + "scope": "api", +} + +# Fake rows for Account_std__dll (used by the default script template). +# Columns: description__c, sfdcorganizationid__c, kq_id__c +_QUERY_RESPONSE = { + "metadata": [ + {"name": "description__c"}, + {"name": "sfdcorganizationid__c"}, + {"name": "kq_id__c"}, + ], + "data": [ + ["hello world", "org123", "kq001"], + ["another row", "org123", "kq002"], + ], +} + + +class MockSFHandler(BaseHTTPRequestHandler): + def _send_json(self, payload: object, status: int = 200) -> None: + body = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, fmt: str, *args: object) -> None: # type: ignore[override] + print(f"[MOCK SF] {self.command} {self.path} — {fmt % args}", flush=True) + + def do_GET(self) -> None: + path = self.path.split("?")[0] + if path == "/services/oauth2/userinfo": + self._send_json(_USERINFO) + else: + self._send_json({"status": "ok"}) + + def do_POST(self) -> None: + path = self.path.split("?")[0] + length = int(self.headers.get("Content-Length", 0)) + body = self.rfile.read(length) if length else b"" + print(f"[MOCK SF] POST body: {body[:200]!r}", flush=True) + + if path == "/services/oauth2/token": + self._send_json(_TOKEN_RESPONSE) + elif path.endswith("/ssot/query-sql"): + self._send_json(_QUERY_RESPONSE) + else: + self._send_json({"status": "ok"}) + + +if __name__ == "__main__": + server = HTTPServer(("localhost", PORT), MockSFHandler) + server.allow_reuse_address = True + print(f"[MOCK SF] Listening on http://localhost:{PORT}", flush=True) + server.serve_forever() From cfe02e7cd9f98e55c2143d48e01bf9a1703cfd16 Mon Sep 17 00:00:00 2001 From: Jesus Orosco Date: Thu, 9 Apr 2026 15:55:04 -0700 Subject: [PATCH 5/8] fake token --- .github/workflows/sf_cli_integration.yml | 2 +- scripts/mock_sf_server.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sf_cli_integration.yml b/.github/workflows/sf_cli_integration.yml index 87d274f..8fb4149 100644 --- a/.github/workflows/sf_cli_integration.yml +++ b/.github/workflows/sf_cli_integration.yml @@ -57,7 +57,7 @@ jobs: - name: Register fake org 'dev1' with SF CLI run: | sleep 1 - echo "fake_access_token_00D000000000001AAA" | \ + echo "00D000000000001AAA!fakeAccessTokenForCITesting" | \ sf org login access-token \ --instance-url http://localhost:8888 \ --alias dev1 \ diff --git a/scripts/mock_sf_server.py b/scripts/mock_sf_server.py index 81fb404..0a699b4 100644 --- a/scripts/mock_sf_server.py +++ b/scripts/mock_sf_server.py @@ -52,7 +52,7 @@ } _TOKEN_RESPONSE = { - "access_token": "fake_access_token_00D000000000001AAA", + "access_token": "00D000000000001AAA!fakeAccessTokenForCITesting", "instance_url": f"http://localhost:{PORT}", "token_type": "Bearer", "scope": "api", From ba334521d93b2ed288af95b17e0422faf65f0907 Mon Sep 17 00:00:00 2001 From: Jesus Orosco Date: Thu, 9 Apr 2026 16:04:09 -0700 Subject: [PATCH 6/8] mock token --- .github/workflows/sf_cli_integration.yml | 39 ++++++++++++++++++++---- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/.github/workflows/sf_cli_integration.yml b/.github/workflows/sf_cli_integration.yml index 8fb4149..7c9fdab 100644 --- a/.github/workflows/sf_cli_integration.yml +++ b/.github/workflows/sf_cli_integration.yml @@ -54,14 +54,41 @@ jobs: env: MOCK_SF_PORT: '8888' - - name: Register fake org 'dev1' with SF CLI + - name: Create fake SF CLI auth for org alias 'dev1' run: | sleep 1 - echo "00D000000000001AAA!fakeAccessTokenForCITesting" | \ - sf org login access-token \ - --instance-url http://localhost:8888 \ - --alias dev1 \ - --no-prompt + python - <<'PYEOF' + import json, pathlib + home = pathlib.Path.home() + + # Auth file — @salesforce/core reads ~/.sfdx/.json on Linux + # (plain-text storage, no OS keychain involved on CI runners) + sfdx_dir = home / ".sfdx" + sfdx_dir.mkdir(exist_ok=True) + auth = { + "accessToken": "00D000000000001AAA!fakeTokenForCITesting", + "instanceUrl": "http://localhost:8888", + "loginUrl": "https://login.salesforce.com", + "orgId": "00D000000000001AAA", + "userId": "005000000000001AAA", + "username": "dev1@example.com", + "clientId": "PlatformCLI", + "isDevHub": False, + "isSandbox": False, + "created": "2024-01-01T00:00:00.000Z", + "createdOrgInstance": "CS1", + } + (sfdx_dir / "dev1@example.com.json").write_text(json.dumps(auth, indent=2)) + + # Alias mapping — write to both locations for compat across sf versions + alias_data = {"orgs": {"dev1": "dev1@example.com"}} + sf_dir = home / ".sf" + sf_dir.mkdir(exist_ok=True) + (sf_dir / "alias.json").write_text(json.dumps(alias_data)) + (sfdx_dir / "alias.json").write_text(json.dumps(alias_data)) + + print("Fake SF CLI org auth written to ~/.sfdx/dev1@example.com.json") + PYEOF # ── Script: init ────────────────────────────────────────────────────────── From db755ca67803c8b4b8c19f095d51f7bb541437cc Mon Sep 17 00:00:00 2001 From: Jesus Orosco Date: Thu, 9 Apr 2026 16:12:16 -0700 Subject: [PATCH 7/8] adding deploy --- .github/workflows/sf_cli_integration.yml | 30 ++++++++++++++ scripts/mock_sf_server.py | 53 +++++++++++++++++++++--- 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/.github/workflows/sf_cli_integration.yml b/.github/workflows/sf_cli_integration.yml index 7c9fdab..b0aaec0 100644 --- a/.github/workflows/sf_cli_integration.yml +++ b/.github/workflows/sf_cli_integration.yml @@ -166,6 +166,21 @@ jobs: exit 1 } + # ── Script: deploy ─────────────────────────────────────────────────────── + + - name: '[script] deploy — sf data-code-extension script deploy' + run: | + sf data-code-extension script deploy \ + --name test-script-deploy \ + --package-version 0.0.1 \ + --description "Test script deploy" \ + --package-dir testScript/payload \ + --cpu-size CPU_2XL \ + -o dev1 || { + echo "::error::sf data-code-extension script deploy FAILED. Check mock server output above for which endpoint failed. The deploy command flags or API contract may have changed." + exit 1 + } + # ── Function: init ──────────────────────────────────────────────────────── - name: '[function] init — sf data-code-extension function init --package-dir testFunction' @@ -244,3 +259,18 @@ jobs: echo "::error::sf data-code-extension function run FAILED. Check mock server output above; the --entrypoint flag or SF CLI org auth contract may have changed." exit 1 } + + # ── Function: deploy ───────────────────────────────────────────────────── + + - name: '[function] deploy — sf data-code-extension function deploy' + run: | + sf data-code-extension function deploy \ + --name test-function-deploy \ + --package-version 0.0.1 \ + --description "Test function deploy" \ + --package-dir testFunction/payload \ + --cpu-size CPU_2XL \ + -o dev1 || { + echo "::error::sf data-code-extension function deploy FAILED. Check mock server output above for which endpoint failed. The deploy command flags or API contract may have changed." + exit 1 + } diff --git a/scripts/mock_sf_server.py b/scripts/mock_sf_server.py index 0a699b4..b296577 100644 --- a/scripts/mock_sf_server.py +++ b/scripts/mock_sf_server.py @@ -1,7 +1,8 @@ """Minimal mock Salesforce server for CI integration tests. -Intercepts the HTTP calls made during ``sf data-code-extension script|function run`` -so that neither a real Salesforce org nor real Data Cloud data is required. +Intercepts the HTTP calls made during ``sf data-code-extension script|function`` +``run`` and ``deploy`` so that neither a real Salesforce org nor real Data Cloud +data is required. Endpoints handled ----------------- @@ -17,6 +18,20 @@ Returns fake rows with the columns expected by the default script template (Account_std__dll: description__c, sfdcorganizationid__c, kq_id__c). +POST /services/data/v63.0/ssot/data-custom-code + Called by deploy_full() → create_deployment(). + Returns a fake fileUploadUrl pointing back at this server. + +GET /services/data/v63.0/ssot/data-custom-code/* + Called by deploy_full() → wait_for_deployment() → get_deployments(). + Returns deploymentStatus=Deployed immediately so the poll loop exits. + +PUT /upload/* + The presigned fileUploadUrl target. Accepts the deployment.zip binary. + +POST /services/data/v63.0/ssot/data-transforms + Called by deploy_full() → create_data_transform() for script packages. + GET /* (catch-all) Returns {"status": "ok"} for any other SF API path the CLI may probe. @@ -72,6 +87,9 @@ ], } +_DATA_CUSTOM_CODE_PATH = "/services/data/v63.0/ssot/data-custom-code" +_DATA_TRANSFORMS_PATH = "/services/data/v63.0/ssot/data-transforms" + class MockSFHandler(BaseHTTPRequestHandler): def _send_json(self, payload: object, status: int = 200) -> None: @@ -82,6 +100,15 @@ def _send_json(self, payload: object, status: int = 200) -> None: self.end_headers() self.wfile.write(body) + def _send_empty(self, status: int = 200) -> None: + self.send_response(status) + self.send_header("Content-Length", "0") + self.end_headers() + + def _drain_body(self) -> bytes: + length = int(self.headers.get("Content-Length", 0)) + return self.rfile.read(length) if length else b"" + def log_message(self, fmt: str, *args: object) -> None: # type: ignore[override] print(f"[MOCK SF] {self.command} {self.path} — {fmt % args}", flush=True) @@ -89,22 +116,38 @@ def do_GET(self) -> None: path = self.path.split("?")[0] if path == "/services/oauth2/userinfo": self._send_json(_USERINFO) + elif path.startswith(_DATA_CUSTOM_CODE_PATH + "/"): + # Deployment status poll — report Deployed immediately + self._send_json({"deploymentStatus": "Deployed"}) else: self._send_json({"status": "ok"}) def do_POST(self) -> None: path = self.path.split("?")[0] - length = int(self.headers.get("Content-Length", 0)) - body = self.rfile.read(length) if length else b"" - print(f"[MOCK SF] POST body: {body[:200]!r}", flush=True) + body = self._drain_body() + print(f"[MOCK SF] POST body: {body[:300]!r}", flush=True) if path == "/services/oauth2/token": self._send_json(_TOKEN_RESPONSE) elif path.endswith("/ssot/query-sql"): + # Data Cloud query (run command) self._send_json(_QUERY_RESPONSE) + elif path == _DATA_CUSTOM_CODE_PATH: + # create_deployment() — return a presigned upload URL + self._send_json( + {"fileUploadUrl": f"http://localhost:{PORT}/upload/fake-deployment.zip"} + ) + elif path == _DATA_TRANSFORMS_PATH: + # create_data_transform() — script packages only + self._send_json({"id": "fake-dt-id", "name": "fake-data-transform"}) else: self._send_json({"status": "ok"}) + def do_PUT(self) -> None: + # upload_zip() sends the deployment.zip to the presigned URL + self._drain_body() + self._send_empty(200) + if __name__ == "__main__": server = HTTPServer(("localhost", PORT), MockSFHandler) From 2fcf3e514a853bfcf572d65ff175a349939716c7 Mon Sep 17 00:00:00 2001 From: Jesus Orosco Date: Thu, 9 Apr 2026 16:15:37 -0700 Subject: [PATCH 8/8] fix deploy function --- .github/workflows/sf_cli_integration.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/sf_cli_integration.yml b/.github/workflows/sf_cli_integration.yml index b0aaec0..b9ff172 100644 --- a/.github/workflows/sf_cli_integration.yml +++ b/.github/workflows/sf_cli_integration.yml @@ -270,6 +270,7 @@ jobs: --description "Test function deploy" \ --package-dir testFunction/payload \ --cpu-size CPU_2XL \ + --function-invoke-opt UnstructuredChunking \ -o dev1 || { echo "::error::sf data-code-extension function deploy FAILED. Check mock server output above for which endpoint failed. The deploy command flags or API contract may have changed." exit 1