### Install Yamale with pip Source: https://github.com/23andme/yamale/blob/master/README.md Install Yamale using pip. To include ruamel.yaml as a dependency, use the `[ruamel]` extra. ```bash pip install yamale ``` ```bash pip install yamale[ruamel] ``` -------------------------------- ### Valid Data for Schema with Optional Keywords Source: https://github.com/23andme/yamale/blob/master/README.md Example data that conforms to the schema with optional keywords. ```yaml optional_min: 10 min: 1.6 max: 100 ``` -------------------------------- ### Schema with Includes and Recursion Source: https://github.com/23andme/yamale/blob/master/README.md Example schema showcasing the use of 'include' for reusable structures and recursive definitions. ```yaml customerA: include('customer') customerB: include('customer') recursion: include('recurse') --- customer: name: str() age: int() custom: include('custom_type') custom_type: integer: int() recurse: level: int() again: include('recurse', required=False) ``` -------------------------------- ### Valid YAML Data for Basic Schema Source: https://github.com/23andme/yamale/blob/master/README.md Example YAML data that conforms to the basic schema definition. ```yaml name: Bill age: 26 height: 6.2 awesome: True ``` -------------------------------- ### Valid Data for Schema with Includes and Recursion Source: https://github.com/23andme/yamale/blob/master/README.md Example data that conforms to the schema with includes and recursive structures. ```yaml customerA: name: bob age: 900 custom: integer: 1 customerB: name: jill age: 1 custom: integer: 3 recursion: level: 1 again: level: 2 again: level: 3 again: level: 4 ``` -------------------------------- ### Schema with Optional Keywords Source: https://github.com/23andme/yamale/blob/master/README.md Example schema demonstrating the use of 'required=False' for optional fields and 'min' keyword for minimum value constraints. ```yaml optional: str(required=False) optional_min: int(min=1, required=False) min: num(min=1.5) max: int(max=100) ``` -------------------------------- ### Use ruamel.yaml Parser Source: https://github.com/23andme/yamale/blob/master/README.md Specify `parser='ruamel'` when creating schema and data objects to enable YAML 1.2 support. Ensure `ruamel.yaml` is installed. ```python # Import Yamale and make a schema object, make sure ruamel.yaml is installed already. import yamale schema = yamale.make_schema('./schema.yaml', parser='ruamel') # Create a Data object data = yamale.make_data('./data.yaml', parser='ruamel') # Validate data against the schema same as before. yamale.validate(schema, data) ``` -------------------------------- ### Valid YAML Data for Schema with Includes Source: https://github.com/23andme/yamale/blob/master/README.md Example YAML data that validates against a schema using the `include` validator. ```yaml person1: name: Bill age: 70 person2: name: Jill age: 20 ``` -------------------------------- ### IP Address Validator Examples Source: https://github.com/23andme/yamale/blob/master/README.md Validates IPv4 and IPv6 addresses. The 'version' keyword can be used to explicitly enforce IPv4 or IPv6. ```python ip() ``` ```python ip(version=4) ``` ```python ip(version=6) ``` -------------------------------- ### Any Validator Examples Source: https://github.com/23andme/yamale/blob/master/README.md Validates against a union of types, accepting a node if it matches at least one of the provided validators. If no validators are given, any value is accepted. ```python any(int(), null()) ``` ```python any(num(), include('vector')) ``` ```python any(str(min=3, max=3),str(min=5, max=5),str(min=7, max=7)) ``` ```python any() ``` -------------------------------- ### Enum Validator Example Source: https://github.com/23andme/yamale/blob/master/README.md Shows the `enum()` validator, which accepts a list of constants as arguments to restrict possible values. The `required` keyword can also be specified. ```yaml enum('a string', 1, False, required=False) ``` -------------------------------- ### Subset Validator Examples Source: https://github.com/23andme/yamale/blob/master/README.md Validates against a subset of types, allowing one or more of the provided validators against a list. The 'allow_empty' keyword makes the subset optional. ```python subset(int(), str()) ``` ```python subset(int(), str(), allow_empty=True) ``` -------------------------------- ### Valid YAML Data for Recursive Schema Source: https://github.com/23andme/yamale/blob/master/README.md Example of nested YAML data that validates against a recursive schema definition. ```yaml person: name: Bill age: 50 friend: name: Jill age: 20 friend: name: Will age: 10 ``` -------------------------------- ### Map Validator Examples Source: https://github.com/23andme/yamale/blob/master/README.md Use the map validator for nodes containing freeform data. It accepts one or more validators for values and optionally a validator for keys. ```python map() ``` ```python map(str(), int()) ``` ```python map(str(), key=int()) ``` ```python map(str(), min=1) ``` -------------------------------- ### Comprehensive Built-in Validator Examples Source: https://context7.com/23andme/yamale/llms.txt Yamale offers a variety of built-in validators for common data types like strings, numbers, booleans, enums, dates, and timestamps. Constraints such as min/max values, length, regular expression matching, and exclusion of specific characters are supported. ```yaml # schema.yaml - Comprehensive validator examples # String validator with constraints username: str(min=3, max=20, matches=r'^[a-z]+$') message: str(exclude='<>', required=False) # Numeric validators age: int(min=0, max=150) price: num(min=0.01, max=9999.99) # Boolean validator active: bool() # Enum validator (must match one of the values) status: enum('pending', 'approved', 'rejected') priority: enum(1, 2, 3) # Date and timestamp validators birth_date: day(min='1900-01-01', max='2024-12-31') created_at: timestamp(min='2020-01-01 00:00:00') ``` -------------------------------- ### Schema with Includes and Recursion Source: https://context7.com/23andme/yamale/llms.txt Demonstrates using `include()` for schema reuse and defining recursive structures for organization trees. ```yaml # schema.yaml - Schema with includes and recursion user: include('person') manager: include('person') organization: include('org_tree') --- # Include definitions (additional YAML documents) person: name: str() email: str(matches=r'^[\w.+-]+@[\w-]+\.[\w.-]+$') age: int(min=18, max=100, required=False) address: include('address', required=False) address: street: str() city: str() country: str() postal_code: str(min=3, max=10) # Recursive schema for tree structures org_tree: name: str() employees: list(include('person'), required=False) departments: list(include('org_tree'), required=False) ``` -------------------------------- ### Create Schema and Data from String Content Source: https://github.com/23andme/yamale/blob/master/README.md Load schema and data directly from YAML strings using the `content` parameter instead of file paths. ```python data = yamale.make_data(content=""" name: Bill age: 26 height: 6.2 awesome: True """) ``` -------------------------------- ### Valid Data for Schema with Includes Source: https://context7.com/23andme/yamale/llms.txt Provides sample data that conforms to the schema defined with `include()` and recursive structures. ```yaml # data.yaml - Valid data for the above schema user: name: Alice Johnson email: alice@company.com age: 28 address: street: 123 Main St city: San Francisco country: USA postal_code: "94102" manager: name: Bob Smith email: bob@company.com organization: name: Engineering employees: - name: Carol Davis email: carol@company.com departments: - name: Frontend employees: - name: Dave Wilson email: dave@company.com - name: Backend departments: - name: API Team ``` -------------------------------- ### Custom Validator Implementation in Python Source: https://context7.com/23andme/yamale/llms.txt Shows how to create custom validators by extending the `Validator` base class and registering them. ```python import yamale import datetime from yamale.validators import DefaultValidators, Validator class Date(Validator): """Validates Python date objects""" tag = 'date' def _is_valid(self, value): return isinstance(value, datetime.date) class Email(Validator): """Validates email format""" tag = 'email' def _is_valid(self, value): import re if not isinstance(value, str): return False pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' return re.match(pattern, value) is not None def fail(self, value): return f"'{value}' is not a valid email address." class NonEmpty(Validator): """Validates non-empty strings""" tag = 'nonempty' def _is_valid(self, value): return isinstance(value, str) and len(value.strip()) > 0 # Register custom validators validators = DefaultValidators.copy() validators[Date.tag] = Date validators[Email.tag] = Email validators[NonEmpty.tag] = NonEmpty # Use custom validators in schema schema = yamale.make_schema(content=""" user_email: email() display_name: nonempty() """, validators=validators) data = yamale.make_data(content=""" user_email: test@example.com display_name: John Doe """, validators=validators) yamale.validate(schema, data) print("Validation passed with custom validators!") ``` -------------------------------- ### Yamale API: Make Schema and Data Objects Source: https://github.com/23andme/yamale/blob/master/README.md Use the Yamale API to create schema and data objects from YAML files. This is the simplest way to use Yamale programmatically. ```python # Import Yamale and make a schema object: import yamale schema = yamale.make_schema('./schema.yaml') # Create a Data object data = yamale.make_data('./data.yaml') ``` -------------------------------- ### Schema with Multiple Root Includes Source: https://github.com/23andme/yamale/blob/master/README.md Demonstrates how multiple root nodes in subsequent YAML documents are treated as separate includes. ```yaml person: include('friend') group: include('family') --- friend: name: str() --- family: name: str() ``` -------------------------------- ### Create Schema Object from File or String Source: https://context7.com/23andme/yamale/llms.txt Use `make_schema` to create a Schema object. It can load schemas from YAML files or directly from string content. Supports custom validators and alternative YAML parsers like ruamel.yaml for YAML 1.2. ```python import yamale # Create schema from a file schema = yamale.make_schema('./schema.yaml') # Create schema from string content schema = yamale.make_schema(content=""" name: str() age: int(min=0, max=150) email: str(matches=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$') active: bool() tags: list(str(), min=1) """) # Create schema with ruamel.yaml parser (YAML 1.2 support) schema = yamale.make_schema('./schema.yaml', parser='ruamel') # Create schema with custom validators from yamale.validators import DefaultValidators, Validator class Percentage(Validator): tag = 'percentage' def _is_valid(self, value): return isinstance(value, (int, float)) and 0 <= value <= 100 validators = DefaultValidators.copy() validators[Percentage.tag] = Percentage schema = yamale.make_schema('./schema.yaml', validators=validators) ``` -------------------------------- ### Validate YAML Files from Command Line Source: https://context7.com/23andme/yamale/llms.txt Use the `yamale` command-line interface for validating YAML files. Supports recursive scanning, pattern exclusion, parallel processing, and custom parsers. ```bash yamale . ``` ```bash yamale config.yaml data/ yamale -s custom_schema.yaml ./configs ``` ```bash yamale -s my_schema.yaml data/ ``` ```bash yamale -e "test_.*\.yaml" -e "fixtures/" . ``` ```bash yamale -p ruamel config.yaml ``` ```bash yamale -n 8 large_config_dir/ yamale -n auto . # Use all available CPUs ``` ```bash yamale -x config.yaml ``` ```bash yamale -v data/ ``` ```bash yamale -V ``` ```bash # Example output for successful validation $ yamale -v ./configs Validating ./configs... Found 15 yaml files to validate... Validation success! ``` ```bash # Example output for failed validation $ yamale invalid_config.yaml Validating invalid_config.yaml... Validation failed! invalid_config.yaml age: '-5' is less than 0 email: 'not-an-email' is not a str match. ``` -------------------------------- ### Yamale Command-Line Usage Source: https://github.com/23andme/yamale/blob/master/README.md Validate YAML files from the command line. Yamale searches for schemas in the same directory as the YAML files or in parent directories. ```bash usage: yamale [-h] [-s SCHEMA] [-e PATTERN] [-p PARSER] [-n CPU_NUM] [-x] [-v] [-V] [PATH ...] Validate yaml files. positional arguments: PATH Paths to validate, either directories or files. Default is the current directory. options: -h, --help show this help message and exit -s SCHEMA, --schema SCHEMA filename of schema. Default is schema.yaml. -e PATTERN, --exclude PATTERN Python regex used to exclude files from validation. Any substring match of a file's absolute path will be excluded. Uses default Python3 regex. Option can be supplied multiple times. -p PARSER, --parser PARSER YAML library to load files. Choices are "ruamel" or "pyyaml" (default). -n CPU_NUM, --cpu-num CPU_NUM Number of child processes to spawn for validation. Default is 4. 'auto' to use CPU count. -x, --no-strict Disable strict mode, unexpected elements in the data will be accepted. -v, --verbose show verbose information -V, --version show program's version number and exit ``` -------------------------------- ### make_data - Load YAML Data for Validation Source: https://context7.com/23andme/yamale/llms.txt Loads YAML data from a file or string content into a format suitable for validation. Returns a list of tuples containing the parsed data and file path, supporting YAML files with multiple documents. ```APIDOC ## make_data - Load YAML Data for Validation ### Description Loads YAML data from a file or string content into a format suitable for validation. Returns a list of tuples containing the parsed data and file path, supporting YAML files with multiple documents. ### Method ```python import yamale # Load data from a file data = yamale.make_data('./config.yaml') # Load data from string content data = yamale.make_data(content=""" name: John Doe age: 30 email: john@example.com active: true tags: - developer - python """) # Load data with ruamel.yaml parser data = yamale.make_data('./config.yaml', parser='ruamel') # Handle multiple YAML documents in one file multi_doc_data = yamale.make_data(content=""" name: Config A --- name: Config B """) # Returns: [({'name': 'Config A'}, None), ({'name': 'Config B'}, None)] ``` ``` -------------------------------- ### Schema with Optional and Non-Nullable Fields Source: https://github.com/23andme/yamale/blob/master/README.md Demonstrates using `required=False` to make a field optional and `none=False` to disallow `None` values for optional fields. ```yaml str(required=False) str(required=False, none=False) ``` -------------------------------- ### Load YAML Data for Validation Source: https://context7.com/23andme/yamale/llms.txt Use `make_data` to load YAML data from files or strings. It returns data in a format suitable for validation and can handle multiple YAML documents within a single file. Supports custom parsers. ```python import yamale # Load data from a file data = yamale.make_data('./config.yaml') # Load data from string content data = yamale.make_data(content=""" name: John Doe age: 30 email: john@example.com active: true tags: - developer - python """) # Load data with ruamel.yaml parser data = yamale.make_data('./config.yaml', parser='ruamel') # Handle multiple YAML documents in one file multi_doc_data = yamale.make_data(content=""" name: Config A --- name: Config B """) # Returns: [({'name': 'Config A'}, None), ({'name': 'Config B'}, None)] ``` -------------------------------- ### make_schema - Create a Schema Object Source: https://context7.com/23andme/yamale/llms.txt Creates a Schema object from a YAML schema file or string content. The schema defines the structure and validation rules that data files must conform to. Supports custom validators and multiple YAML parsers. ```APIDOC ## make_schema - Create a Schema Object ### Description Creates a Schema object from a YAML schema file or string content. The schema defines the structure and validation rules that data files must conform to. Supports custom validators and multiple YAML parsers. ### Method ```python import yamale # Create schema from a file schema = yamale.make_schema('./schema.yaml') # Create schema from string content schema = yamale.make_schema(content=""" name: str() age: int(min=0, max=150) email: str(matches=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$') active: bool() tags: list(str(), min=1) """) # Create schema with ruamel.yaml parser (YAML 1.2 support) schema = yamale.make_schema('./schema.yaml', parser='ruamel') # Create schema with custom validators from yamale.validators import DefaultValidators, Validator class Percentage(Validator): tag = 'percentage' def _is_valid(self, value): return isinstance(value, (int, float)) and 0 <= value <= 100 validators = DefaultValidators.copy() validators[Percentage.tag] = Percentage schema = yamale.make_schema('./schema.yaml', validators=validators) ``` ``` -------------------------------- ### Add External Includes to Schema Object Source: https://github.com/23andme/yamale/blob/master/README.md Dynamically add external include definitions to an existing schema object by passing a dictionary to `schema.add_include()`. ```python schema.add_include(dict) ``` -------------------------------- ### Valid Data for List of Objects Schema Source: https://github.com/23andme/yamale/blob/master/README.md Provide data that conforms to the schema for a list of two 'human' objects. ```yaml - name: Bill age: 26 height: 6.2 awesome: True - name: Adrian age: 23 height: 6.3 awesome: True ``` -------------------------------- ### String Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md Use the `str` validator for strings. It supports length constraints (`min`, `max`), exact matching (`equals`), prefix/suffix checks (`starts_with`, `ends_with`), regex matching (`matches`), exclusion of characters (`exclude`), and case-insensitive comparisons (`ignore_case`). The `multiline` and `dotall` keywords are only applicable when using the `matches` keyword. ```python str(max=10, exclude='?!') ``` -------------------------------- ### Add External Includes Programmatically to Yamale Schema Source: https://context7.com/23andme/yamale/llms.txt Dynamically add include definitions to a Yamale schema after its creation using the `add_include()` method. This is useful for managing shared include libraries or dynamically generated schemas. ```python import yamale # Create base schema schema = yamale.make_schema(content=""" config: include('settings') user: include('person') """) # Add include definitions programmatically schema.add_include({ 'settings': { 'debug': 'bool()', 'log_level': "enum('DEBUG', 'INFO', 'WARNING', 'ERROR')", 'max_connections': 'int(min=1, max=1000)' }, 'person': { 'name': 'str(min=1)', 'role': "enum('admin', 'user', 'guest')" } }) # Validate data against schema with dynamic includes data = yamale.make_data(content=""" config: debug: true log_level: INFO max_connections: 100 user: name: Admin role: admin """) yamale.validate(schema, data) print("Validation with dynamic includes passed!") ``` -------------------------------- ### Schema with Includes for Reusable Structures Source: https://github.com/23andme/yamale/blob/master/README.md Defines reusable structures ('person') using the `include` validator. Additional YAML documents after the first are treated as includes. ```yaml person1: include('person') person2: include('person') --- person: name: str() age: int() ``` -------------------------------- ### Integer Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md Use the `int` validator to ensure values are integers. It supports minimum (`min`) and maximum (`max`) value constraints. ```python int(min=1, max=10) ``` -------------------------------- ### Schema with Recursion using Include Source: https://github.com/23andme/yamale/blob/master/README.md Implements recursion within a schema using the `include` validator, allowing for nested or self-referential structures. ```yaml person: include('human') --- human: name: str() age: int() friend: include('human', required=False) ``` -------------------------------- ### SemVer Validator Source: https://github.com/23andme/yamale/blob/master/README.md Allows any valid SemVer (Semantic Versioning) string. ```python semver() ``` -------------------------------- ### Validate Data Against Schema Source: https://context7.com/23andme/yamale/llms.txt Use `validate` to check data against a schema. By default, it raises `YamaleError` on failure. Options include non-strict mode to ignore unexpected fields and `_raise_error=False` to return results instead of exceptions. ```python import yamale from yamale import YamaleError # Basic validation (raises YamaleError on failure) schema = yamale.make_schema('./schema.yaml') data = yamale.make_data('./data.yaml') yamale.validate(schema, data) # Validation with error handling schema = yamale.make_schema(content=""" name: str() age: int(min=0) """) data = yamale.make_data(content=""" name: Alice age: -5 """) try: yamale.validate(schema, data) print('Validation success!') except YamaleError as e: print('Validation failed!') for result in e.results: print(f"Error validating data '{result.data}' with '{result.schema}'") for error in result.errors: print(f" - {error}") # Output: age: -5 is less than 0 # Non-strict mode (allow unexpected elements) schema = yamale.make_schema(content="name: str()") data = yamale.make_data(content=""" name: Bob extra_field: ignored """) yamale.validate(schema, data, strict=False) # Passes validation # Get results without raising exception results = yamale.validate(schema, data, _raise_error=False) for result in results: if result.isValid(): print(f"Valid: {result.data}") else: print(f"Invalid: {result.errors}") ``` -------------------------------- ### MAC Address Validator Source: https://github.com/23andme/yamale/blob/master/README.md Allows any valid MAC address. ```python mac() ``` -------------------------------- ### Valid Data for Mixed List Schema Source: https://github.com/23andme/yamale/blob/master/README.md Provide data that conforms to the schema allowing strings and specific object types within a list. ```yaml list_with_two_types: - 'some' - rsid: 'rs123' name: 'some SNP' - 'thing' - rsid: 'rs312' name: 'another SNP' questions: - choices: - id: 'id_str' - id: 'id_str1' questions: - choices: - id: 'id_str' - id: 'id_str1' ``` -------------------------------- ### Basic Yamale Schema Definition Source: https://github.com/23andme/yamale/blob/master/README.md A simple schema defining expected data types for 'name', 'age', 'height', and 'awesome'. ```yaml name: str() age: int(max=200) height: num() awesome: bool() ``` -------------------------------- ### Schema with Mixed List Types Source: https://github.com/23andme/yamale/blob/master/README.md Define a schema for a list that can contain strings or objects matching a specific type. ```yaml list_with_two_types: list(str(), include('variant')) questions: list(include('question')) --- variant: rsid: str() name: str() question: choices: list(include('choices')) questions: list(include('question'), required=False) choices: id: str() ``` -------------------------------- ### Schema for List of Objects Source: https://github.com/23andme/yamale/blob/master/README.md Define a schema for a list where each item must be an object of type 'human' and the list must contain exactly two items. ```yaml list(include('human'), min=2, max=2) --- human: name: str() age: int(max=200) height: num() awesome: bool() ``` -------------------------------- ### Validate Data Against Schema Source: https://github.com/23andme/yamale/blob/master/README.md Use `yamale.validate()` to check if data conforms to a schema. Throws a ValueError on invalid data. ```python yamale.validate(schema, data) ``` -------------------------------- ### Include Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates included structures by referencing a defined include name. ```python include('person') ``` -------------------------------- ### Handle Validation Errors with ValueError Source: https://github.com/23andme/yamale/blob/master/README.md Catch `ValueError` during validation to handle cases where the data does not match the schema. Prints validation errors. ```python try: yamale.validate(schema, data) print('Validation success! 👍') except ValueError as e: print('Validation failed!\n%s' % str(e)) exit(1) ``` -------------------------------- ### Regex Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates strings against one or more regular expressions. ```APIDOC ## Regex Validator ### Description Validates strings against one or more regular expression patterns, with options for naming, case sensitivity, and multiline/dotall modes. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Arguments - **patterns** (string) - Required - One or more Python regular expression patterns. #### Keywords - **name** (string) - Optional - A friendly description for the patterns. - **ignore_case** (boolean) - Optional - Default: `False`. Perform case-insensitive matching. - **multiline** (boolean) - Optional - Default: `False`. Enable multiline mode for pattern matching. - **dotall** (boolean) - Optional - Default: `False`. Enable dotall mode for pattern matching. ### Request Example ```json { "example": "regex('^[^?!]{,10}$')" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Basic Yamale Validators Source: https://context7.com/23andme/yamale/llms.txt Defines validators for lists, maps, IP addresses, MAC addresses, regex patterns, semantic versions, and flexible types. ```yaml tags: list(str(), min=1, max=10) scores: list(int(min=0, max=100)) metadata: map(str(), key=str(min=1)) counts: map(int(), min=1) server_ip: ip(version=4) ipv6_addr: ip(version=6) device_mac: mac() phone: regex(r'^\+?[1-9]\d{1,14}$', name='phone number') version: semver() flexible: any(str(), int(), null()) permissions: subset(str(), int()) deleted_at: null() ``` -------------------------------- ### Regex Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md The `regex` validator checks strings against one or more regular expressions. It accepts patterns as arguments and supports keywords like `name` for description, `ignore_case` for case-insensitivity, and `multiline`/`dotall` for advanced regex behavior. The `multiline` and `dotall` keywords affect how `^`, `$`, and `.` behave within the regex patterns. ```python regex('^[^?!]{,10}$') ``` ```python regex(r'^(\d+)(\s\1)+$', name='repeated natural') ``` ```python regex('.*^apples$', multiline=True, dotall=True) ``` -------------------------------- ### Integrate Yamale Validation with YamaleTestCase Source: https://context7.com/23andme/yamale/llms.txt Use YamaleTestCase to integrate YAML file validation into your Python unit tests. Define schema and yaml file paths directly within the test class. ```python import os from yamale import YamaleTestCase class TestConfigSchema(YamaleTestCase): """Test that all config files match the schema""" base_dir = os.path.dirname(os.path.realpath(__file__)) schema = 'schemas/config_schema.yaml' yaml = 'configs/config.yaml' def runTest(self): self.assertTrue(self.validate()) ``` ```python class TestMultipleConfigs(YamaleTestCase): """Test multiple config files with globs""" base_dir = '/path/to/project' schema = 'schema.yaml' yaml = ['configs/*.yaml', 'overrides/production.yaml'] def runTest(self): self.assertTrue(self.validate()) ``` ```python class TestWithCustomValidators(YamaleTestCase): """Test with custom validators""" schema = 'custom_schema.yaml' yaml = 'custom_data.yaml' def runTest(self): from yamale.validators import DefaultValidators, Validator class UUID(Validator): tag = 'uuid' def _is_valid(self, value): import re pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' return isinstance(value, str) and re.match(pattern, value.lower()) validators = DefaultValidators.copy() validators[UUID.tag] = UUID self.assertTrue(self.validate(validators=validators)) ``` -------------------------------- ### Null Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md Use the `null` validator to ensure a value is null. It does not accept any arguments or keywords. ```python null() ``` -------------------------------- ### YamaleTestCase for Validation Source: https://github.com/23andme/yamale/blob/master/README.md Use YamaleTestCase to validate YAML files within Python tests. Specify base directory, schema, and YAML files for validation. ```python import os from yamale.yamale_testcase import YamaleTestCase class TestYaml(YamaleTestCase): base_dir = os.path.dirname(os.path.realpath(__file__)) schema = 'schema.yaml' yaml = 'data.yaml' # or yaml = ['data-*.yaml', 'some_data.yaml'] def runTest(self): self.assertTrue(self.validate()) ``` -------------------------------- ### Day Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md Validate dates in 'YYYY-MM-DD' format using the `day` validator. It supports `min` and `max` keywords to specify a date range. ```python day(min='2001-01-01', max='2100-01-01') ``` -------------------------------- ### Integer Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates integer data types with minimum and maximum value constraints. ```APIDOC ## Integer Validator ### Description Validates integer values, allowing specification of minimum and maximum allowed values. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Keywords - **min** (int) - Optional - Minimum allowed integer value. - **max** (int) - Optional - Maximum allowed integer value. ### Request Example ```json { "example": "int(min=1, max=100)" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Handle Validation Errors with YamaleError Source: https://github.com/23andme/yamale/blob/master/README.md Catch `YamaleError` for more detailed error reporting, iterating through results and specific errors for each invalid node. ```python try: yamale.validate(schema, data) print('Validation success! 👍') except YamaleError as e: print('Validation failed!\n') for result in e.results: print("Error validating data '%s' with '%s'\n\t" % (result.data, result.schema)) for error in result.errors: print('\t%s' % error) exit(1) ``` -------------------------------- ### validate - Validate Data Against Schema Source: https://context7.com/23andme/yamale/llms.txt Validates loaded data against a schema. By default, raises a `YamaleError` if validation fails. Supports strict mode to reject unexpected elements and can return results instead of raising exceptions. ```APIDOC ## validate - Validate Data Against Schema ### Description Validates loaded data against a schema. By default, raises a `YamaleError` if validation fails. Supports strict mode to reject unexpected elements and can return results instead of raising exceptions. ### Method ```python import yamale from yamale import YamaleError # Basic validation (raises YamaleError on failure) schema = yamale.make_schema('./schema.yaml') data = yamale.make_data('./data.yaml') yamale.validate(schema, data) # Validation with error handling schema = yamale.make_schema(content=""" name: str() age: int(min=0) """) data = yamale.make_data(content=""" name: Alice age: -5 """) try: yamale.validate(schema, data) print('Validation success!') except YamaleError as e: print('Validation failed!') for result in e.results: print(f"Error validating data '{result.data}' with '{result.schema}'") for error in result.errors: print(f" - {error}") # Output: age: -5 is less than 0 # Non-strict mode (allow unexpected elements) schema = yamale.make_schema(content="name: str()") data = yamale.make_data(content=""" name: Bob extra_field: ignored """) yamale.validate(schema, data, strict=False) # Passes validation # Get results without raising exception results = yamale.validate(schema, data, _raise_error=False) for result in results: if result.isValid(): print(f"Valid: {result.data}") else: print(f"Invalid: {result.errors}") ``` ``` -------------------------------- ### Number Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md The `num` validator validates both integers and floating-point numbers. It accepts `min` and `max` keywords to define the acceptable range. ```python num(min=0.0, max=100.0) ``` -------------------------------- ### Day Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates dates in YYYY-MM-DD format, with optional minimum and maximum date constraints. ```APIDOC ## Day Validator ### Description Validates date strings in the 'YYYY-MM-DD' format, with optional minimum and maximum date ranges. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Keywords - **min** (date) - Optional - Minimum allowed date (YYYY-MM-DD). - **max** (date) - Optional - Maximum allowed date (YYYY-MM-DD). ### Request Example ```json { "example": "day(min='2001-01-01', max='2100-01-01')" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### String Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates string data types with various constraints. ```APIDOC ## String Validator ### Description Validates strings with options for length, exact match, prefix, suffix, regex matching, exclusion, and case sensitivity. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Keywords - **min** (int) - Optional - Minimum length of the string. - **max** (int) - Optional - Maximum length of the string. - **equals** (string) - Optional - Exact string value the string must match. - **starts_with** (string) - Optional - String must start with this value. - **ends_with** (string) - Optional - String must end with this value. - **matches** (regex) - Optional - String must match the provided regular expression. - **exclude** (string) - Optional - String must not contain any character from this value. - **ignore_case** (boolean) - Optional - Default: `False`. Perform case-insensitive comparisons. - **multiline** (boolean) - Optional - Default: `False`. Enable multiline mode for `matches`. - **dotall** (boolean) - Optional - Default: `False`. Enable dotall mode for `matches`. ### Request Example ```json { "example": "str(max=10, exclude='?!')" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Timestamp Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md Use the `timestamp` validator for values in 'YYYY-MM-DD HH:MM:SS' format. It allows defining a time range using `min` and `max` keywords. ```python timestamp(min='2001-01-01 01:00:00', max='2100-01-01 23:00:00') ``` -------------------------------- ### List Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates list data types with optional constraints on minimum/maximum length and item validators. ```APIDOC ## List Validator ### Description Validates lists, with options for minimum and maximum length, and for specifying validators for list items. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Arguments - **validators** (validator) - Optional - One or more validators to test list items against. #### Keywords - **min** (int) - Optional - Minimum number of items in the list. - **max** (int) - Optional - Maximum number of items in the list. ### Request Example ```json { "example": "list(int(), min=4)" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Null Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates null values. ```APIDOC ## Null Validator ### Description Validates that a value is `null`. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "example": "null()" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Built-in Validators Source: https://context7.com/23andme/yamale/llms.txt Yamale provides validators for common data types including strings, numbers, booleans, dates, lists, maps, enums, IP addresses, and more. All validators accept `required` and `none` keyword arguments. ```APIDOC ## Built-in Validators ### Description Yamale provides validators for common data types including strings, numbers, booleans, dates, lists, maps, enums, IP addresses, and more. All validators accept `required` and `none` keyword arguments. ### Schema Examples ```yaml # schema.yaml - Comprehensive validator examples # String validator with constraints username: str(min=3, max=20, matches=r'^[a-z]+$') message: str(exclude='<>', required=False) # Numeric validators age: int(min=0, max=150) price: num(min=0.01, max=9999.99) # Boolean validator active: bool() # Enum validator (must match one of the values) status: enum('pending', 'approved', 'rejected') priority: enum(1, 2, 3) # Date and timestamp validators birth_date: day(min='1900-01-01', max='2024-12-31') created_at: timestamp(min='2020-01-01 00:00:00') ``` ``` -------------------------------- ### Boolean Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md The `bool` validator checks if a value is a boolean (True or False). It does not accept any arguments or keywords. ```python bool() ``` -------------------------------- ### List Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md The `list` validator checks if a value is a list and can optionally enforce minimum (`min`) and maximum (`max`) lengths. You can also provide validators as arguments to ensure elements within the list conform to specific types or rules. ```python list() ``` ```python list(include('custom'), int(), min=4) ``` -------------------------------- ### Timestamp Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates timestamps in YYYY-MM-DD HH:MM:SS format, with optional minimum and maximum timestamp constraints. ```APIDOC ## Timestamp Validator ### Description Validates timestamp strings in the 'YYYY-MM-DD HH:MM:SS' format, with optional minimum and maximum timestamp ranges. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Keywords - **min** (time) - Optional - Minimum allowed timestamp (YYYY-MM-DD HH:MM:SS). - **max** (time) - Optional - Maximum allowed timestamp (YYYY-MM-DD HH:MM:SS). ### Request Example ```json { "example": "timestamp(min='2001-01-01 01:00:00', max='2100-01-01 23:00:00')" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Number Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates numeric data types (integers and floats) with minimum and maximum value constraints. ```APIDOC ## Number Validator ### Description Validates both integer and float values, with optional minimum and maximum bounds. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Keywords - **min** (float) - Optional - Minimum allowed numeric value. - **max** (float) - Optional - Maximum allowed numeric value. ### Request Example ```json { "example": "num(min=0.0, max=100.5)" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Boolean Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates boolean data types. ```APIDOC ## Boolean Validator ### Description Validates that a value is a boolean (`true` or `false`). ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "example": "bool()" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Enum Validator Source: https://github.com/23andme/yamale/blob/master/README.md Validates that a value is one of a predefined list of constants. ```APIDOC ## Enum Validator ### Description Validates that a value matches one of the provided constant values. ### Method N/A (This is a validator definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Arguments - **primitives** (any) - Required - One or more constants to test equality with. ### Request Example ```json { "example": "enum('a string', 1, False)" } ``` ### Response N/A (This is a validator definition) ``` -------------------------------- ### Enum Validation with Yamale Source: https://github.com/23andme/yamale/blob/master/README.md The `enum` validator checks if a value is present in a provided list of constants. Pass the allowed constants as arguments to the `enum` function. ```python enum('a string', 1, False) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.