Search code examples
pythontranscrypt

assert not working as expected


Here is the python code I transcrypted with transcrypt -b -n -m (version 3.6.84) :

def test_1():
    console.log('before assert')
    assert False, "False fails"
    console.log('we should not see that if assert fails as expected')


def test_2():
    console.log('before assert')
    try:
        assert False, "False fails"
    except AssertionError as exception:
        console.log('we should see that since we catch the assertion error')
    console.log('after assert')

When I run test_1/test_2 in the browser console, I get a strange behavior :

> mymodule.test_1()
before assert
we should not see that if assert fails as expected
<- undefined
> mymodule.test_2()
before assert
after assert
<- undefined

Why no exception are raised with assert ?


Solution

  • Answer from issue 482 :

    You need the -da switch to activate assertions:

    transcrypt -b -n -m -da

    I've tested:

    def test_1():
        console.log('before assert')
        assert False, "False fails"
        console.log('we should not see that if assert fails as expected')
    
    def test_2():
        console.log('before assert')
        try:
            assert False, "False fails"
        except AssertionError as exception:
            console.log('we should see that since we catch the assertion error')
        console.log('after assert')
    
    try:    
        test_1()
    except AssertionError as exception:
        console.log('we should see this')
    
    test_2()
    

    It prints:

    before assert
    we should see this
    before assert
    we should see that since we catch the assertion error
    after assert
    

    Many things in Transcrypt are optional, to prevent bloat of the generated JavaScript. Some features are controlled by command line switches:

    http://www.transcrypt.org/docs/html/installation_use.html#available-command-line-switches

    Some features are (also) controlled by pragma's (compiler directives):

    http://www.transcrypt.org/docs/html/special_facilities.html#the-pragma-mechanism