1- """
2- This example demonstrates how to develop new rules.
3- """
4-
51# Copyright © 2025 Brockmann Consult GmbH.
62# This software is distributed under the terms and conditions of the
73# MIT license (https://mit-license.org/).
84
5+ """
6+ This example demonstrates how to develop new rules.
7+ """
8+
99import xarray as xr
1010
1111from xrlint .node import DatasetNode
1212from xrlint .rule import RuleContext , RuleOp , define_rule
1313from xrlint .testing import RuleTest , RuleTester
1414
1515
16+ # ----------------------------------------------------
17+ # Place the rule implementation code in its own module
18+ # ----------------------------------------------------
19+
20+
1621@define_rule ("good-title" )
1722class GoodTitle (RuleOp ):
1823 """Dataset title should be 'Hello World!'."""
1924
25+ # We just validate the dataset instance here. You can also implement
26+ # the validation of other nodes in this class, e.g.,
27+ # validate_datatree(), validate_variable(), validate_attrs(),
28+ # and validate_attr().
29+ #
2030 def validate_dataset (self , ctx : RuleContext , node : DatasetNode ):
2131 good_title = "Hello World!"
2232 if node .dataset .attrs .get ("title" ) != good_title :
@@ -26,27 +36,34 @@ def validate_dataset(self, ctx: RuleContext, node: DatasetNode):
2636 )
2737
2838
29- # -----------------
30- # In another module
31- # -----------------
39+ # ---------------------------------------------------
40+ # Place the following rule test code in a test module
41+ # ---------------------------------------------------
3242
3343tester = RuleTester ()
3444
3545valid_dataset = xr .Dataset (attrs = dict (title = "Hello World!" ))
3646invalid_dataset = xr .Dataset (attrs = dict (title = "Hello Hamburg!" ))
3747
38- # Run test directly
48+ # You can use the tester to run a test directly
49+ #
3950tester .run (
4051 "good-title" ,
4152 GoodTitle ,
4253 valid = [RuleTest (dataset = valid_dataset )],
54+ # We expect one message to be emitted
4355 invalid = [RuleTest (dataset = invalid_dataset , expected = 1 )],
4456)
4557
46- # or define a test class derived from unitest.TestCase
58+ # ... or generate a test class that will be derived from `unitest.TestCase`.
59+ # This will provide you tooling support via your test runner, e.g., pytest,
60+ # as the tests in `valid` and `invalid` will be transformed into
61+ # test methods of the generated class.
62+ #
4763GoodTitleTest = tester .define_test (
4864 "good-title" ,
4965 GoodTitle ,
5066 valid = [RuleTest (dataset = valid_dataset )],
51- invalid = [RuleTest (dataset = invalid_dataset )],
67+ # Note, here we expect a specific message to be emitted
68+ invalid = [RuleTest (dataset = invalid_dataset , expected = ["Attribute 'title' wrong." ])],
5269)
0 commit comments