Handle int modulo by 0 and add tests

This commit is contained in:
TJ Miller 2023-03-09 15:59:12 -08:00
parent 16997769e0
commit c0fd3fe38b
3 changed files with 54 additions and 0 deletions

View File

@ -35,3 +35,38 @@ a: !!float 2
b: 2.5
```
## Number modulo - int by zero
If the lhs is an int and rhs is a 0 the result is an error.
Given a sample.yml file of:
```yaml
a: 1
b: 0
```
then
```bash
yq '.a = .a % .b' sample.yml
```
will output
```bash
Error: cannot modulo by 0
```
## Number modulo - float by zero
If the lhs is a float and rhs is a 0 the result is NaN.
Given a sample.yml file of:
```yaml
a: 1.1
b: 0
```
then
```bash
yq '.a = .a % .b' sample.yml
```
will output
```yaml
a: !!float NaN
b: 0
```

View File

@ -68,6 +68,9 @@ func moduloScalars(context Context, target *CandidateNode, lhs *yaml.Node, rhs *
if err != nil {
return err
}
if rhsNum == 0 {
return fmt.Errorf("cannot modulo by 0")
}
remainder := lhsNum % rhsNum
target.Node.Tag = lhs.Tag

View File

@ -40,6 +40,22 @@ var moduloOperatorScenarios = []expressionScenario{
"D0, P[], (doc)::{a: !!float 2, b: 2.5}\n",
},
},
{
description: "Number modulo - int by zero",
subdescription: "If the lhs is an int and rhs is a 0 the result is an error.",
document: `{a: 1, b: 0}`,
expression: `.a = .a % .b`,
expectedError: "cannot modulo by 0",
},
{
description: "Number modulo - float by zero",
subdescription: "If the lhs is a float and rhs is a 0 the result is NaN.",
document: `{a: 1.1, b: 0}`,
expression: `.a = .a % .b`,
expected: []string{
"D0, P[], (doc)::{a: !!float NaN, b: 0}\n",
},
},
{
skipDoc: true,
description: "Custom types: that are really numbers",