Skip to content

Instantly share code, notes, and snippets.

@dunossauro
Created September 21, 2020 18:27
Show Gist options
  • Save dunossauro/b234afb66664a0d4f11d7c7e04af0018 to your computer and use it in GitHub Desktop.
Save dunossauro/b234afb66664a0d4f11d7c7e04af0018 to your computer and use it in GitHub Desktop.
Kivy unittesting

Tree

/
  /main.py
  /test
    test_app.py

Run tests

pytest

Run coverage

coverage -m pytest
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
class MyBox(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.btn1 = Button(
text="Btn 1",
on_press=self.btn_press,
on_release=self.btn_release
)
self.btn2 = Button(
text="Btn 2",
on_press=self.btn_press,
on_release=self.btn_release
)
self.lbl = Label()
self.lbl.text = "Label"
self.add_widget(self.btn1)
self.add_widget(self.btn2)
self.add_widget(self.lbl)
def btn_press(self, instance):
self.lbl.text = f'apertou {instance.text.lower()}'
def btn_release(self, instance):
self.lbl.text = f'soltou {instance.text.lower()}'
class TestApp(App):
def build(self):
return MyBox()
if __name__ == "__main__":
TestApp().run()
from contextlib import contextmanager
from kivy.base import EventLoop
from kivy.tests.common import GraphicUnitTest, UnitTestTouch
from main import MyBox
@contextmanager
def touch(btn):
t = UnitTestTouch(*btn.center)
t.touch_down()
yield
t.touch_up()
@contextmanager
def window_loop():
EventLoop.ensure_window()
yield EventLoop.window.children[0]
class BoxGraphicUnitTest(GraphicUnitTest):
def setUp(self, *args, **kwargs):
super().setUp(*args, **kwargs)
self.box = MyBox()
self.render(self.box)
class TestMyBox(BoxGraphicUnitTest):
box = MyBox()
def test_prees_btn1(self):
with touch(self.box.btn1):
assert self.box.lbl.text == 'apertou btn 1'
assert self.box.lbl.text == 'soltou btn 1'
def test_prees_btn2(self):
with touch(self.box.btn2):
assert self.box.lbl.text == 'apertou btn 2'
assert self.box.lbl.text == 'soltou btn 2'
def test_window_components(self):
with window_loop() as window:
assert window.children[0] == self.box.lbl
assert window.children[1] == self.box.btn2
assert window.children[2] == self.box.btn1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment