1

I want to write a property-based unit test that proves that the integer subtraction is not commutative. I have this with mocha and fast-check:

const fc = require('fast-check')

describe('The subtraction', () => {
    it('is not commutative', () => {
        fc.assert(
            fc.property(
                fc.integer(), fc.integer(), (a, b) => a - b !== b - a
            )
        )
    })
})

After several runs I noticed that it fails when the condition a === b && a <= 0 is true. However, I am not sure if there are any other conditions that do not comply with a - b !== b - a, so I am not sure if excluding that specific condition is right.

How can I write the test? Should I exclude the specific condition? Or should I check that at a - b !== b - a is true for at least two given values? Or is there any other way to test it?

Examples using any other kind of javascript libraries for property-based testing are welcome too.

Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
  • 4
    This is me not knowing something perhaps, but for an n-ary (say binary) operation op to not commute it simply amounts to showing there is a, b such that a op b != b op a. So you simply need to demo a single example, at least in my mind, does property-based testing ordain that you should do things in as great a generality as possible? In general if a - b === b - a if and only if a === b – Countingstuff Jan 14 '19 at 22:37
  • @Countingstuff I am starting with property-based testing, but it seems to be the case, to test as generally as possible, by only describing the behavior. It may be as a mathematical demonstration I think. – Guillermo Gutiérrez Jan 14 '19 at 22:43
  • What is the point of testing to see whether the subtraction operation is commutative? Are you trying to find CPU faults? Runtime bugs? If so you'll have to test every possible number pair, which is going to require more than a few bags of popcorn. – Pointy Jan 14 '19 at 22:44
  • Also note that there isn't "integer subtraction" in JavaScript (setting aside the new "bigint" stuff, which isn't widely available). The common numeric operators perform 64-bit floating point operations. – Pointy Jan 14 '19 at 22:46
  • @Pointy this is just a general example. The reason is to learn to test similar cases, like when a property should comply for at least one case, or given some pre-conditions. – Guillermo Gutiérrez Jan 14 '19 at 22:57
  • 2
    Well if you can think of *any* pair of numbers for which the reverse operation is different, you're done. For generalized operations, a value-by-value exhausitve test would be the only thing to do, so I'd *still* think that an analytical proof would be much preferred. – Pointy Jan 14 '19 at 23:04

0 Answers0