# Leveraging the Power of OpenMetadata Data Quality Framework

Nov 17, 2023 · 7 min read

![](https://lh3.googleusercontent.com/a/ACg8ocKdjKyZzubpMxDIRi5sriH1HzkWomhxilfaVJ_cvIp0nSzmBoA=s96-c)ércule team

![Leveraging the Power of OpenMetadata Data Quality Framework](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fuploads%2Fgql%2F6a2ba683b960f45f04f3cf5e%2Fe28083de-0730-43cd-b47d-6b090f4439b0.png&w=3840&q=75)

OpenMetadata offers the possibility to execute data quality tests directly from the UI, making it a powerful tool for everyone in the company. With close to 30 table and column tests, OpenMetadata makes it easy for everyone to own data quality.

![](https://cdn.hashnode.com/uploads/gql/6a2ba683b960f45f04f3cf5e/fc5edbe8-de8b-4685-872b-46a0afce89d3.png)

We understand that teams can use third-party tools, or have custom data quality rules. That is why we offer-third party integration with dbt and Great Expectations, and comprehensive API integration to ingest all your test results into the platform.

![](https://cdn.hashnode.com/uploads/gql/6a2ba683b960f45f04f3cf5e/86d4d586-acd2-4d97-b288-52cf7248bf98.png)

Now you may ask yourself, “What if I want to extend OpenMetadata tests, and define custom tests that can be set up and executed directly from the UI”? Then look no further. With OpenMetadata Data Quality Framework, you can define your data quality tests and make them available to all your users.

\*\*Disclaimer: \*\*You will need to work with the OpenMetadata API and write some Python code. You won’t need extensive knowledge of these two concepts; only basic familiarity with them will be enough.

The first step is to create your test definition. A test definition describes the different elements of your test (e.g., name, description, parameter, etc.). You will define this new test definition as shown below.

```
{
    "description": "<you test definition description>",
    "entityType": "<TABLE|COLUMN>",
    "name": "<your_test_name>",
    "displayName": "<your display name>",
    "testPlatforms": ["OpenMetadata"],
    "supportedDataTypes": ["NUMBER|TEXT|CHAR"],
    "parameterDefinition": [
      {
        "name": "<name>",
        "displayName": "<display name>",
        "description": "<desription of the test>",
        "optionValues": ["optionOne", "optionTwo"],
      },
      {
        "name": "<name>",
        "displayName": "<display name>",
        "description": "<desription of the test>",
        "optionValues": ["optionOne", "optionTwo"],
      }
    ]
}

```

Let’s go over each element one by one:

1.  `description`: this is the description of your test. It will provide your users with more information and details
2.  `entityType`: set `TABLE` if you are defining a table-level test or `COLUMN` if you are defining a column-level test
3.  `name`: the name of your test definition. It should be unique across all test definitions
4.  `displayName`: the name of your test definition as it will appear in OpenMetadata UI
5.  `testPlatforms`: this is an array of test platforms. To make your test executable through OpenMetadata, this should be set to `OpenMetadata`
6.  `supportedDataTypes`: (optional) pass a list of supported data types for your test definition. This will limit the ability for users to create the test only against columns with supported data types. The complete list of data type values can be found [here](https://github.com/open-metadata/OpenMetadata/blob/222a8f898451f6dc7dafc7bfda232d91c21209cf/openmetadata-spec/src/main/resources/json/schema/entity/data/table.json#L74-L147).
7.  `parameterDefinition`: a list of parameters that will be used to configure a test `name`: the name of your parameter `displayName`: the display name of your parameter as it will appear in the UI `description`: the description for your parameter. This will be used to populate the tooltip in the UI `optionValues`: If you want to make your parameter value a selectable value from a dropdown menu ![](https://cdn.hashnode.com/uploads/gql/6a2ba683b960f45f04f3cf5e/29d12834-ba7e-4d9c-908c-b95384760991.png)

Once you have defined your test definition using the JSON template above, you must make the test available in OpenMetadata. Making it available in OpenMetadata will make your test usable through the UI. Users can navigate to the test creation page and select it from the dropdown menu.

For this step, you will need a way to send an API `POST` request to your OpenMetadata server endpoint`/api/v1/dataQuality/testDefinitions`. For this example, we’ll use `curl` (more info about `curl` [here](https://curl.se/docs/)).

**Test Definition**

```
{
    "description": "Compute entropy for a given column",
    "displayName": "Column Entropy To Be Between",
    "entityType": "COLUMN",
    "name": "columnEntropyToBeBetween",
    "testPlatforms": ["OpenMetadata"],
    "parameterDefinition": [
      {
        "name": "minEntropy",
        "displayName": "Min",
        "dataType": "INT",
        "required": true,
        "description": "minimum entropy"
      },
      {
        "name": "maxEntropy",
        "displayName": "Max",
        "dataType": "INT",
        "required": true,
        "description": "maximum entropy"
      }
    ]
}

```

**`curl` Reque**st

```
curl --location --request POST '<yourServerHost>/api/v1/dataQuality/testDefinitions' \
--header 'Authorization: Bearer <yourJWTToken>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "description": "Compute entropy for a given column",
    "displayName": "Column Entropy To Be Between",
    "entityType": "COLUMN",
    "name": "columnEntropyToBeBetween",
    "testPlatforms": ["OpenMetadata"],
    "parameterDefinition": [
      {
        "name": "minEntropy",
        "displayName": "Min",
        "dataType": "INT",
        "required": true,
        "description": "minimum entropy"
      },
      {
        "name": "maxEntropy",
        "displayName": "Max",
        "dataType": "INT",
        "required": true,
        "description": "maximum entropy"
      }
    ]
}'

```

You will need to replace `<yourServerHost>` with the URL where the OpenMetadata server is hosted (e.g., `http://localhost:8558` if you are working with a local installation). You will also need to replace `<yourJWTToken>` with your personal JWT Token (i.e., go to `settings > bot` to find your JWT Token or generate one).

![](https://cdn.hashnode.com/uploads/gql/6a2ba683b960f45f04f3cf5e/27add0fe-de2f-41fd-a7e0-577b0c6782e4.png)

Now that we have created our new test definition, we’ll need to tell OpenMetadata how we want to process and execute this test. To accomplish this, we can leverage OpenMetadata Data Quality Framework.

**Step 1 — Create a Python Package**

The first step is to create a new Python package. This will allow you to version control your custom tests and add unit tests. As we’ll be leveraging Python `namesapce` package, our package needs to have a specific structure.

-   For a column level test: `<yourFolderName>/metadata/data_quality/validations/columns/<sqlalchemy|pandas>/yourTestName.py`
-   `<yourFolderName>/metadata/data_quality/validations/table/<sqlalchemy|pandas>/yourTestName.py` Use `pandas` if you are writing a test that will be used for data lake connectors; otherwise, use `sqlalchemy` for all other database connectors

For our column entropy test, our folder structure will look like this

```
folderName/
├── setup.py
└── metadata/
    ├── __init__.py
    └── data_quality/
        ├── __init__.py
        └── validations/
            ├── __init__.py
            └── column/
                ├── __init__.py
                └── sqlalchemy/
                    ├── __init__.py
                    └── columnEntropyToBeBetween.py

```

**Important:** note how our test file name matches the above test definition name. This is important to respect.

**Step 2 — `setup.py` and `__init__.py` f**iles

For your `setup.py` file, you will, at minimum, need to call the `setup` function calling `find_packages()` for the `packages` argument.

For our entropy test, we have added the requirements needed to execute our test (e.g., `scipy` )

```
from setuptools import find_packages, setup

base_requirements = ["scipy"]
setup(name='custom-tests',
      version='0.0.1',
      description='OpenMetadata Custom Tests',
      packages=find_packages(),
      install_requires=list(base_requirements)
     )

```

Finally, you must add the line below to all your `__init__.py` files. This tells Python that we are working with `namespace` packages (this is at the core of OpenMetadata flexible Data Quality Framework).

```
__path__ = __import__('pkgutil').extend_path(__path__, __name__)

```

**Step 3 — Defining your Test Execution Logic**

One of the last two missing pieces to our puzzle is adding the logic to execute our test. You will need to create a new class name `<YourTestName>Validator` that will inherit from `BaseTestValidator`.

You will then need to implement the `run_validation` method where your core logic is being executed.

```
from itertools import chain
from sqlalchemy import Column, inspect
from scipy import stats
from metadata.data_quality.validations.base_test_handler import BaseTestValidator
from metadata.generated.schema.tests.basic import TestCaseResult, TestResultValue
from metadata.utils.entity_link import get_decoded_column

class ColumnEntropyToBeBetweenValidator(BaseTestValidator):
    """Implements custom test validator for OpenMetadata.
    Args:
        BaseTestValidator (_type_): inherits from BaseTestValidator
    """
    def _get_column_name(self) -> Column:
        """get column name from the test case entity link
        Returns:
            Column: column
        """
        column = get_decoded_column(self.test_case.entityLink.__root__)
        columns = inspect(self.runner.table).c
        column_obj = next(
            (col for col in columns if col.name == column),
            None,
        )
        if column_obj is None:
            raise ValueError(f"Cannot find column {column}")
        return column_obj

    def run_validation(self) -> TestCaseResult:
        """Run test validation"""
        rows = self.runner.select_all_from_table(self._get_column_name())
        list_of_values = list(chain.from_iterable(rows))
        entropy = stats.entropy(list_of_values)
        min_bound = self.get_min_bound("minEntropy")
        max_bound = self.get_max_bound("maxEntropy")
        return self.get_test_case_result_object(
            self.execution_date,
            self.get_test_case_status(min_bound <= entropy <= max_bound),
            f"Found entropy={entropy} vs. the expected  min={min_bound} and max={max_bound}].",
            [TestResultValue(name="entropy", value=str(entropy))],
        )

```

For our entropy test above, we created our new class ColumnEntropyToBeBetweenValidator, which inherits from `BaseTestValidator`. We then implemented `run_validation,` fetching the rows from our table column with `self.runner.select_all_from_tabl(self._get_column_name())`. `self._get_column_name()` fetches the column for which our test was created. We then compute the entropy for the column `stats.entropy(list_of_values)`. Finally, we fetch the min and max bounds that were set `self.get_min_bound("minEntropy")` — note how the argument we pass to `get_<min|max>_bound` corresponds to the `name` of our test definition. Finally, we call `self.get_test_case_result_object(...)` which will return the status of our test alongside other information.

**Step 4 — Install your package in your environment**

Finally, you must install your package where your OpenMetadata ingestion is running using `pip install <...>`.

If you enjoy OpenMetadata and want to contribute new tests to the community, you can head to our [GitHub Repo](https://github.com/open-metadata/OpenMetadata), browse the [Data Quality code](https://github.com/open-metadata/OpenMetadata/tree/main/ingestion/src/metadata/data_quality), and open a new PR. 😊

![](https://cdn.hashnode.com/uploads/gql/6a2ba683b960f45f04f3cf5e/f0abc490-2566-405b-aa27-a99b392481a3.png)

[#data-governance](/blog/tag/data-governance)[#data-engineering](/blog/tag/data-engineering)[#data-catalog](/blog/tag/data-catalog)[#data-quality](/blog/tag/data-quality)[#data-quality-management](/blog/tag/data-quality-management)

## Share this article

[](https://twitter.com/intent/post?url=https%3A%2F%2Fopen-metadata.org%2Fblog%2Fleveraging-the-power-of-openmetadata-data-quality-framework%3Fref%3Dtwitter-share)[](https://www.linkedin.com/feed/?linkOrigin=LI_BADGE&shareActive=true&shareUrl=https%3A%2F%2Fopen-metadata.org%2Fblog%2Fleveraging-the-power-of-openmetadata-data-quality-framework)