How to test timestamp or other context on onchain views

The following question has been asked on Telegram:

Hello everyone! Is there a way to have a timestamp when unit testing an onchain_view. For entrypoints, one can run it like:
contract.entrypoint(parameter).run(now=sp.timestamp(100), sender=account)

I don’t see any documentation on being able to have fake timestamps when unit testing on-chain views

1 Like

You can change the scenario now by using scenario.compute("", now=...) and then call your on-chain view.

Example:

import smartpy as sp

@sp.module
def main():
    class MyContract(sp.Contract):
        def __init__(self):
            pass

        @sp.entrypoint
        def ep(self):
            pass

        @sp.onchain_view
        def get_now(self):
            return sp.now

if "templates" not in __name__:
    @sp.add_test(name="MyContract")
    def test():
        sc = sp.test_scenario(main)
        c1 = main.MyContract()
        sc += c1
        c1.ep()
        sc.compute("", now=sp.timestamp(5))
        now = sp.View(c1, "get_now")()
        sc.verify_equal(now, sp.timestamp(5))
1 Like