Sublime Forum

Open_file synchronously

#1

I am writing a test where i need to open a file and assert some operation but the issue is sublime.active_window().open_file opens file async due to which i have to loop and check whether the view is created or not.

Is there any better way to do this? because of this looping on view.is_loading sometimes freezes up the whole test run.

test_file_view = sublime.active_window().open_file(
            fname='test_fixture.py'
      )
)

        # wait for view to open
        while test_file_view.is_loading():
            pass
0 Likes

#2

Assuming tests are executed via UnitTesting, the following would be possible.

The DeferrableViewTestCase already provides an empty view for each test. So opening a file via python API and assigning result to view would work.

from unittesting import DeferrableViewTestCase


class MyViewTests(DeferrableViewTestCase):
    def test_with_file():
        with open("path/to/file.txt", encoding="utf-8") as file:
            self.setText(file.read())

        self.assertViewContentsEqual("content of file.txt")
0 Likes

#3

This would’ve worked, but my use case is little different, i need an actual file to open as view, because the plugin only works on saved file.

0 Likes

#4

Ok for now i have solved the issue by opening file async and using the UnitTest plugin yield to wait for file to open

test_file_view = None

def open_test_fixture_file():
    test_file_view = sublime.active_window().open_file(
        fname='test_fixture.py'
    )

    # wait for view to open
    while test_file_view.is_loading():
        pass


sublime.set_timeout_async(open_test_fixture_file, 0)
try:
    # Wait 4 second to make sure test fixture file has opened
    yield 4000
except TimeoutError as e:
    pass

# It will have the view object now
test_file_view
0 Likes

#5

The following might work as well

import sublime
from unittesting import DeferrableTestCase


class TestDeferrable(DeferrableTestCase):

    def test_with_fixture(self):
        test_file_view = sublime.active_window().open_file(
            fname='test_fixture.py'
        )
        # wait not more than 5s for file to be loaded
        yield {"condition": lambda: not test_file_view.is_loading, "timeout": 5000}

        # assertions
        # ...

        # finally close the view (note, that won't work if exceptions are raised)
        test_file_view.close()

Note: using sublime.active_window() in each test might have unwanted side effects if active window changes while unittesting is running. It’s probably better to initially assign or create a window for testing.

1 Like

#6

Understood thanks for the advice on active_window bit

0 Likes