Skip to content

Added export CLI functionality for assessment results #2553

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 93 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
93 commits
Select commit Hold shift + click to select a range
4f0c6dc
initial draft of remote dashboads widgets collection
rportilla-databricks Aug 26, 2024
d288e0a
Creating new branch without committing any files
rportilla-databricks Aug 27, 2024
5aee6b6
Cherry-pick commit 60f957e
rportilla-databricks Aug 27, 2024
afc714c
test
lmallepaddi Aug 27, 2024
ad01abb
test commit
lmallepaddi Aug 27, 2024
f26c522
Added UCX Export Result notebook as Utility Hack
jgarciaf106 Aug 29, 2024
522d43e
add test files
rportilla-databricks Aug 30, 2024
0c7083d
updated unit tests
rportilla-databricks Sep 3, 2024
66dbab1
Merge pull request #1 from rportilla-databricks/feat/ucx-export-notebook
rportilla-databricks Sep 3, 2024
32adee0
Update workflows.py
jgarciaf106 Sep 3, 2024
77a88cd
Merge pull request #3 from rportilla-databricks/feat/add_exporter
rportilla-databricks Sep 3, 2024
9db2d70
Merge pull request #2 from rportilla-databricks/export-notebook-patch-1
rportilla-databricks Sep 4, 2024
33f1f11
Adding unit tests coverage
lmallepaddi Sep 4, 2024
898eeef
fullset unit test cases and slight changes to export.py file
lmallepaddi Sep 5, 2024
2c8e92b
Removed unnecessary imports
lmallepaddi Sep 5, 2024
d6243ad
Merge pull request #4 from rportilla-databricks/feat/add_exporter
rportilla-databricks Sep 6, 2024
99bf9a1
updated tests
rportilla-databricks Sep 6, 2024
ee446f1
update cli for export
rportilla-databricks Sep 7, 2024
e57cbfe
update test format
rportilla-databricks Sep 7, 2024
1240c63
Merge branch 'main' into main
rportilla-databricks Sep 7, 2024
5cdeb3c
Update src/databricks/labs/ucx/assessment/export.py
rportilla-databricks Sep 9, 2024
c63904e
add structural changes
rportilla-databricks Sep 10, 2024
8b71454
Integrated lsql functionality to export the Assessment Results
jgarciaf106 Sep 11, 2024
a8a325e
Minor Changes
jgarciaf106 Sep 11, 2024
6ebc90c
Merge branch 'main' into feat/cli-assessment-export
rportilla-databricks Sep 11, 2024
f47f125
Merge pull request #7 from jgarciaf106/feat/cli-assessment-export
rportilla-databricks Sep 11, 2024
cd67ee4
naming change missed in cli.py
rportilla-databricks Sep 11, 2024
3e8d342
correcting use of the cached property
rportilla-databricks Sep 11, 2024
92fd1c0
fix cached property
rportilla-databricks Sep 11, 2024
e5e2e10
fix cli
rportilla-databricks Sep 11, 2024
a71b086
Removed flags as there are code provides prompts
lmallepaddi Sep 11, 2024
21785e4
added command line usage in readme file
lmallepaddi Sep 12, 2024
077a03f
Merge pull request #8 from rportilla-databricks/feat/add_exporter
rportilla-databricks Sep 12, 2024
14fa408
minor change to export.py to resolve unit test case issue
lmallepaddi Sep 12, 2024
8d607c8
fix errors and address feedback
rportilla-databricks Sep 12, 2024
20c19f2
updated syntax for export
rportilla-databricks Sep 12, 2024
cf6fa3c
Merge branch 'main' into feat/add_exporter
lmallepaddi Sep 12, 2024
6a33aca
Update src/databricks/labs/ucx/cli.py
rportilla-databricks Sep 12, 2024
7b798aa
Update src/databricks/labs/ucx/installer/workflows.py
rportilla-databricks Sep 12, 2024
66c281f
Update workflows.py
jgarciaf106 Sep 12, 2024
a00ecf8
Merge pull request #10 from rportilla-databricks/Workflows-patch-3
rportilla-databricks Sep 12, 2024
92937ce
revert tmp path
rportilla-databricks Sep 12, 2024
b4d58d5
changes to README.md and test_export.py
lmallepaddi Sep 12, 2024
4599dfa
Merge pull request #9 from rportilla-databricks/feat/add_exporter
rportilla-databricks Sep 15, 2024
dce6f86
Merge branch 'databrickslabs:main' into feat/add_exporter
rportilla-databricks Sep 15, 2024
d61a5ce
Merge branch 'databrickslabs:main' into main
rportilla-databricks Sep 15, 2024
8c7dd67
Merge pull request #11 from rportilla-databricks/feat/add_exporter
rportilla-databricks Sep 15, 2024
d94d581
update the logical name of the collection of queries
rportilla-databricks Sep 16, 2024
007891d
update reference
rportilla-databricks Sep 16, 2024
598c596
Updated notebook content to Use triple quotes
jgarciaf106 Sep 16, 2024
82146db
Merge pull request #12 from rportilla-databricks/export_notebook/patch
rportilla-databricks Sep 16, 2024
f4b7170
zip file rename functionality
lmallepaddi Sep 17, 2024
90a8189
changed readme file to reflect changes to zipfilename
lmallepaddi Sep 17, 2024
5eb417c
Changes to export.py using lsql version 0.11
lmallepaddi Sep 19, 2024
9069f3d
updated the test_cli.py for filename change
lmallepaddi Sep 19, 2024
44b4ac4
remove print statement
rportilla-databricks Sep 23, 2024
bcfd6e1
Merge pull request #13 from rportilla-databricks/feat/add_exporter
rportilla-databricks Sep 23, 2024
f90d2c1
Merge branch 'main' into main
nfx Sep 23, 2024
6e3ddf9
Export Results simplification
jgarciaf106 Sep 24, 2024
26799fc
Merge pull request #14 from rportilla-databricks/patch-export
rportilla-databricks Sep 25, 2024
b2e3c85
Fixed Unit Tests for Export Assessment
jgarciaf106 Sep 25, 2024
9fb3f49
Merge pull request #15 from rportilla-databricks/patch-export
rportilla-databricks Sep 25, 2024
3d567b4
Merge branch 'databrickslabs:main' into main
rportilla-databricks Sep 26, 2024
ae5832d
make fmt run
rportilla-databricks Sep 26, 2024
204ab4a
Minor contributor documentation changes (#2729)
asnare Sep 24, 2024
0a6e72f
Handle `PermissionDenied` when listing accessible workspaces (#2733)
JCZuurmond Sep 24, 2024
93d496e
Adding unskip CLI command to undo a skip on schema or a table (#2727)
aminmovahed-db Sep 24, 2024
ee20112
Fix failing integration tests that perform a real assessment (#2736)
ericvergnaud Sep 24, 2024
2f62a0f
Update documentation to explain the usage of collections and eligible…
HariGS-DB Sep 24, 2024
8fee9d8
Enables cli cmd `databricks labs ucx create-catalog-schemas` to apply…
HariGS-DB Sep 24, 2024
21da7cc
Add `create-ucx-catalog` cli command (#2694)
JCZuurmond Sep 25, 2024
2a09a8f
Fixes issue of circular dependency of migrate-location ACL (#2741)
HariGS-DB Sep 25, 2024
d1dd0c5
Added static code analysis results to assessment dashboard (#2696)
ericvergnaud Sep 25, 2024
7cba9b0
Increases test coverage (#2739)
pritishpai Sep 25, 2024
04a4956
Fixes source table alias dissapearance during migrate_views (#2726)
pritishpai Sep 25, 2024
15c5536
Bump astroid version, pylint version and drop our f-string workaround…
ericvergnaud Sep 25, 2024
2611b11
Update databricks-labs-blueprint requirement from <0.9,>=0.8 to >=0.8…
dependabot[bot] Sep 25, 2024
555e83a
Delete temporary files when running solacc (#2750)
ericvergnaud Sep 25, 2024
d744465
Code format: `make fmt` (#2749)
asnare Sep 25, 2024
04918be
Speedup assessment workflow by making DBFS root table size calculatio…
nfx Sep 25, 2024
0a03def
Harden configuration reading (#2701)
JCZuurmond Sep 26, 2024
be955ea
Add unskip CLI command to undo a skip on schema or a table (#2734)
aminmovahed-db Sep 26, 2024
788c273
Improve solacc linting (#2752)
ericvergnaud Sep 26, 2024
1d12391
Sync Fork, make fmt test
jgarciaf106 Sep 26, 2024
d3a0e39
Merge pull request #16 from rportilla-databricks/patch-export-v2
rportilla-databricks Sep 27, 2024
4d2e9a6
Merge branch 'databrickslabs:main' into main
rportilla-databricks Sep 27, 2024
b163801
Added CLI Functionality to export UCX Assessment
jgarciaf106 Sep 30, 2024
188bc24
Added CLI Functionality to export UCX Assessment
jgarciaf106 Sep 30, 2024
cb89541
Added CLI Functionality to export UCX Assessment
jgarciaf106 Sep 30, 2024
571fc8b
Added CLI Functionality to export UCX Assessment
jgarciaf106 Sep 30, 2024
77786a2
Merge branch 'main' into feat/add-cli-export-assessment-reviewed
rportilla-databricks Oct 2, 2024
84830fd
Merge pull request #21 from jgarciaf106/feat/add-cli-export-assessmen…
rportilla-databricks Oct 2, 2024
2975950
Merge branch 'main' into main
jgarciaf106 Oct 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ so that you'll be able to [scope the migration](docs/assessment.md) and execute
The [README notebook](#readme-notebook), which can be found in the installation folder contains further instructions and explanations of the different ucx workflows & dashboards.
Once the migration is scoped, you can start with the [table migration process](#Table-Migration).


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove redundant newlines

More workflows, like notebook code migration are coming in future releases.


UCX also provides a number of command line utilities accessible via `databricks labs ucx`.

For questions, troubleshooting or bug fixes, please see our [troubleshooting guide](docs/troubleshooting.md) or submit [an issue](https://github.com/databrickslabs/ucx/issues).
Expand Down Expand Up @@ -90,6 +92,7 @@ See [contributing instructions](CONTRIBUTING.md) to help improve this project.
* [`open-remote-config` command](#open-remote-config-command)
* [`installations` command](#installations-command)
* [`report-account-compatibility` command](#report-account-compatibility-command)
* [`export-assessment` command](#export-assessment-command)
* [Metastore related commands](#metastore-related-commands)
* [`show-all-metastores` command](#show-all-metastores-command)
* [`assign-metastore` command](#assign-metastore-command)
Expand Down Expand Up @@ -1167,6 +1170,42 @@ databricks labs ucx report-account-compatibility --profile labs-azure-account
12:56:21 INFO [d.l.u.account.aggregate] Non-DELTA format: UNKNOWN: 5 objects
```

[[back to top](#databricks-labs-ucx)]
## `export-assessment` command

```commandline
databricks labs ucx export-assessment
```
The export-assessment command is used to export UCX assessment results to a specified location. When you run this command, you will be prompted to provide details on the destination path and the type of report you wish to generate. If you do not specify these details, the command will default to exporting the main results to the current directory. The exported file will be named based on the selection made in the format. Eg: export_{query_choice}_results.zip
- **Choose a path to save the UCX Assessment results:**
- **Description:** Specify the path where the results should be saved. If not provided, results will be saved in the current directory.

- **Choose which assessment results to export:**
- **Description:** Select the type of results to export. Options include:
- `azure`
- `estimates`
- `interactive`
- `main`
- **Default:** `main`

[[back to top](#databricks-labs-ucx)]

## `export-assessment` command

```commandline
databricks labs ucx export-assessment
```
The export-assessment command is used to export UCX assessment results to a specified location. When you run this command, you will be prompted to provide details on the destination path and the type of report you wish to generate. If you do not specify these details, the command will default to exporting the main results to the current directory. The exported file will be named based on the selection made in the format. Eg: export_{query_choice}_results.zip
- **Choose a path to save the UCX Assessment results:**
- **Description:** Specify the path where the results should be saved. If not provided, results will be saved in the current directory.

- **Choose which assessment results to export:**
- **Description:** Select the type of results to export. Options include:
- `azure`
- `estimates`
- `interactive`
- `main`

[[back to top](#databricks-labs-ucx)]

# Metastore related commands
Expand Down
3 changes: 3 additions & 0 deletions labs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -330,3 +330,6 @@ commands:
description: The file to download
- name: run-as-collection
description: Run the command for the collection of workspaces with ucx installed. Default is False.

- name: export-assessment
description: Export UCX results to a specified location
48 changes: 48 additions & 0 deletions src/databricks/labs/ucx/assessment/export.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import logging
from pathlib import Path

from databricks.labs.blueprint.tui import Prompts

from databricks.labs.ucx.config import WorkspaceConfig
from databricks.labs.lsql.backends import SqlBackend
from databricks.labs.lsql.dashboards import DashboardMetadata

logger = logging.getLogger(__name__)


class AssessmentExporter:

def __init__(self, sql_backend: SqlBackend, config: WorkspaceConfig):
self._sql_backend = sql_backend
self._config = config

def export_results(self, prompts: Prompts):
"""Main method to export results to CSV files inside a ZIP archive."""
project_root = Path(__file__).resolve().parents[3]
queries_path_root = project_root / "labs/ucx/queries/assessment"

results_directory = Path(
prompts.question(
"Choose a path to save the UCX Assessment results",
default=Path.cwd().as_posix(),
validate=lambda p_: Path(p_).exists(),
)
)

query_choice = prompts.choice(
"Choose which assessment results to export",
[subdir.name for subdir in queries_path_root.iterdir() if subdir.is_dir()],
)

export_path = results_directory / f"export_{query_choice}_results.zip"
queries_path = queries_path_root / query_choice

assessment_results = DashboardMetadata.from_path(queries_path).replace_database(
database=self._config.inventory_database, database_to_replace="inventory"
)

logger.info("Exporting assessment results....")
results_path = assessment_results.export_to_zipped_csv(self._sql_backend, export_path)
logger.info(f"Results exported to {results_path}")

return results_path
9 changes: 9 additions & 0 deletions src/databricks/labs/ucx/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from databricks.labs.ucx.install import AccountInstaller
from databricks.labs.ucx.source_code.linters.files import LocalCodeLinter


ucx = App(__file__)
logger = get_logger(__file__)

Expand Down Expand Up @@ -791,5 +792,13 @@ def lint_local_code(
linter.lint(prompts, None if path is None else Path(path))


@ucx.command
def export_assessment(w: WorkspaceClient, prompts: Prompts):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like a duplicate of the above command?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed now.

"""Export the UCX assessment queries to a zip file."""
ctx = WorkspaceContext(w)
exporter = ctx.assessment_exporter
exporter.export_results(prompts)


if __name__ == "__main__":
ucx()
7 changes: 6 additions & 1 deletion src/databricks/labs/ucx/contexts/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

from databricks.labs.ucx.account.workspaces import WorkspaceInfo
from databricks.labs.ucx.assessment.azure import AzureServicePrincipalCrawler
from databricks.labs.ucx.assessment.export import AssessmentExporter
from databricks.labs.ucx.aws.credentials import CredentialManager
from databricks.labs.ucx.config import WorkspaceConfig
from databricks.labs.ucx.hive_metastore import ExternalLocations, Mounts, TablesCrawler
Expand Down Expand Up @@ -260,7 +261,11 @@ def tables_migrator(self) -> TablesMigrator:
)

@cached_property
def acl_migrator(self) -> ACLMigrator:
def assessment_exporter(self):
return AssessmentExporter(self.sql_backend, self.config)

@cached_property
def acl_migrator(self):
return ACLMigrator(
self.tables_crawler,
self.workspace_info,
Expand Down
128 changes: 128 additions & 0 deletions src/databricks/labs/ucx/installer/workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,123 @@
f'--parent_run_id=' + dbutils.widgets.get('parent_run_id'))
"""

EXPORT_TO_EXCEL_NOTEBOOK = """# Databricks notebook source
# MAGIC %md
# MAGIC ##### Exporter of UCX assessment results
# MAGIC ##### Instructions:
# MAGIC 1. Execute using an all-purpose cluster with Databricks Runtime 14 or higher.
# MAGIC 1. Hit **Run all** button and wait for completion.
# MAGIC 1. Go to the bottom of the notebook and click the Download UCX Results button.
# MAGIC
# MAGIC ##### Important:
# MAGIC Please note that this is only meant to serve as example code.
# MAGIC
# MAGIC Example code developed by **Databricks Shared Technical Services team**.

# COMMAND ----------

# DBTITLE 1,Installing Packages
# MAGIC %pip install {remote_wheel} -qqq
# MAGIC %pip install xlsxwriter -qqq
# MAGIC dbutils.library.restartPython()

# COMMAND ----------

# DBTITLE 1,Libraries Import and Setting UCX
import os
import logging
import threading
import shutil
from pathlib import Path
from threading import Lock
from functools import partial

import pandas as pd
import xlsxwriter

from databricks.sdk.config import with_user_agent_extra
from databricks.labs.blueprint.logger import install_logger
from databricks.labs.blueprint.parallel import Threads
from databricks.labs.lsql.dashboards import Dashboards
from databricks.labs.lsql.lakeview.model import Dataset
from databricks.labs.ucx.contexts.workflow_task import RuntimeContext

# ctx
install_logger()
with_user_agent_extra("cmd", "export-assessment")
named_parameters = dict(config="/Workspace{config_file}")
ctx = RuntimeContext(named_parameters)
lock = Lock()

# COMMAND ----------

# DBTITLE 1,Assessment Export
FILE_NAME = "ucx_assessment_main.xlsx"
TMP_PATH = f"/Workspace{{ctx.installation.install_folder()}}/tmp/"
DOWNLOAD_PATH = "/dbfs/FileStore/excel-export"


def _cleanup() -> None:
'''Move the temporary results file to the download path and clean up the temp directory.'''
shutil.move(
os.path.join(TMP_PATH, FILE_NAME),
os.path.join(DOWNLOAD_PATH, FILE_NAME),
)
shutil.rmtree(TMP_PATH)


def _prepare_directories() -> None:
'''Ensure that the necessary directories exist.'''
os.makedirs(TMP_PATH, exist_ok=True)
os.makedirs(DOWNLOAD_PATH, exist_ok=True)


def _to_excel(dataset: Dataset, writer: ...) -> None:
'''Execute a SQL query and write the result to an Excel sheet.'''
worksheet_name = dataset.display_name[:31]
df = spark.sql(dataset.query).toPandas()
with lock:
df.to_excel(writer, sheet_name=worksheet_name, index=False)


def _render_export() -> None:
'''Render an HTML link for downloading the results.'''
html_content = '''
<style>@font-face{{font-family:'DM Sans';src:url(https://cdn.bfldr.com/9AYANS2F/at/p9qfs3vgsvnp5c7txz583vgs/dm-sans-regular.ttf?auto=webp&format=ttf) format('truetype');font-weight:400;font-style:normal}}body{{font-family:'DM Sans',Arial,sans-serif}}.export-container{{text-align:center;margin-top:20px}}.export-container h2{{color:#1B3139;font-size:24px;margin-bottom:20px}}.export-container a{{display:inline-block;padding:12px 25px;background-color:#1B3139;color:#fff;text-decoration:none;border-radius:4px;font-size:18px;font-weight:500;transition:background-color 0.3s ease,transform:translateY(-2px) ease}}.export-container a:hover{{background-color:#FF3621;transform:translateY(-2px)}}</style>
<div class="export-container"><h2>Export Results</h2><a href='{workspace_host}/files/excel-export/ucx_assessment_main.xlsx?o={workspace_id}' target='_blank' download>Download Results</a></div>

'''
displayHTML(html_content)


def export_results() -> None:
'''Main method to export results to an Excel file.'''
_prepare_directories()

dashboard_path = (
Path(ctx.installation.install_folder())
/ "dashboards/[UCX] UCX Assessment (Main).lvdash.json"
)
dashboard = Dashboards(ctx.workspace_client)
dashboard_datasets = dashboard.get_dashboard(dashboard_path).datasets
try:
target = TMP_PATH + "/ucx_assessment_main.xlsx"
with pd.ExcelWriter(target, engine="xlsxwriter") as writer:
tasks = []
for dataset in dashboard_datasets:
tasks.append(partial(_to_excel, dataset, writer))
Threads.strict("exporting", tasks)
_cleanup()
_render_export()
except Exception as e:
print(f"Error exporting results ", e)

# COMMAND ----------

# DBTITLE 1,Data Export
export_results()
"""


class DeployedWorkflows:
def __init__(self, ws: WorkspaceClient, install_state: InstallState):
Expand Down Expand Up @@ -484,6 +601,7 @@ def create_jobs(self) -> None:
self.remove_jobs(keep=desired_workflows)
self._install_state.save()
self._create_debug(remote_wheels)
self._create_export(remote_wheels)
self._create_readme()

def remove_jobs(self, *, keep: set[str] | None = None) -> None:
Expand Down Expand Up @@ -822,6 +940,16 @@ def _create_debug(self, remote_wheels: list[str]):
).encode("utf8")
self._installation.upload('DEBUG.py', content)

def _create_export(self, remote_wheels: list[str]):
remote_wheels_str = " ".join(remote_wheels)
content = EXPORT_TO_EXCEL_NOTEBOOK.format(
remote_wheel=remote_wheels_str,
config_file=self._config_file,
workspace_host=self._ws.config.host,
workspace_id=self._ws.get_workspace_id(),
).encode("utf8")
self._installation.upload('EXPORT_ASSESSMENT_TO_EXCEL.py', content)


class MaxedStreamHandler(logging.StreamHandler):

Expand Down
41 changes: 41 additions & 0 deletions tests/unit/assessment/test_export.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from databricks.labs.ucx.config import WorkspaceConfig
from databricks.labs.ucx.assessment.export import AssessmentExporter
from databricks.labs.lsql.backends import MockBackend
from databricks.labs.blueprint.tui import MockPrompts
from databricks.labs.lsql.core import Row


def test_export(tmp_path):
"""Test the export_results method of the AssessmentExporter class."""
query = {
"SELECT\n one\nFROM ucx.external_locations": [
Row(location="s3://bucket1/folder1", table_count=1),
Row(location="abfss://container1@storage1.dfs.core.windows.net/folder1", table_count=1),
Row(location="gcp://folder1", table_count=2),
]
}

# Setup workspace configuration
config = WorkspaceConfig(inventory_database="ucx")

# Prepare temporary paths and files
export_path = tmp_path / "export"
export_path.mkdir(parents=True, exist_ok=True)

# Mock backend and prompts
mock_backend = MockBackend(rows=query)
query_choice = {"assessment_name": "main", "option": 3}
mock_prompts = MockPrompts(
{
"Choose a path to save the UCX Assessment results": export_path.as_posix(),
"Choose which assessment results to export": query_choice["option"],
}
)

# Execute export process
export = AssessmentExporter(mock_backend, config)
exported = export.export_results(mock_prompts)

# Assertion based on the query_choice
expected_file_name = f"export_{query_choice['assessment_name']}_results.zip" # Adjusted filename
assert exported == export_path / expected_file_name
17 changes: 17 additions & 0 deletions tests/unit/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
validate_groups_membership,
workflows,
delete_missing_principals,
export_assessment,
)
from databricks.labs.ucx.contexts.account_cli import AccountContext
from databricks.labs.ucx.contexts.workspace_cli import WorkspaceContext
Expand Down Expand Up @@ -1133,3 +1134,19 @@ def test_delete_principals(ws):
prompts = MockPrompts({"Select the list of roles *": "0"})
delete_missing_principals(ws, prompts, ctx)
role_creation.delete_uc_roles.assert_called_once()


def test_export_assessment(ws, tmp_path):
query_choice = {"assessment_name": "main", "option": 3}
mock_prompts = MockPrompts(
{
"Choose a path to save the UCX Assessment results": tmp_path.as_posix(),
"Choose which assessment results to export": query_choice["option"],
}
)

export_assessment(ws, mock_prompts)
# Construct the expected filename based on the query_choice
expected_filename = f"export_{query_choice['assessment_name']}_results.zip"
# Assert that the file exists in the temporary path
assert len(list(tmp_path.glob(expected_filename))) == 1
Loading