Skip to content

Testing scripts

For quality purposes, you may want to write automated tests for your openOBD scripts. When testing the scripts, there is no need to talk to an actual openOBD server. You can create a mock object instead.

This page lists an example how to create and use a mock grpc implementation in your unit tests.

Creating a mock openOBD implementation

Below is an example implementation of an openOBD mock. The first snippet defines a mock implementation of the canService. The implementation will create a stream that listens to incoming messages and returns the same message, as soon as a message arrives.

Another approach might be to use the python unittest mock library to define the behaviour of the methods.

from openobd_protocol.Communication import CommunicationServices_pb2_grpc as grpcCommunicationService

class CanEchoService(grpcCommunicationService.canServicer):
    def __init__(self):
        super().__init__()

    def openRawStream(self, request_iterator, *args):
        for message in request_iterator:
            if message.payload != "":
                yield message

    def openIsotpStream(self, request_iterator, *args):
        for message in request_iterator:
            yield message

The second snippet defines an implementation of the GrpcFactory. This factory will return a mock instance for the canService, that just echoes the input. The default GrpcFactory class will return implementations that raise a NotImplementedError for each method. This means that only the method that are overridden in the mock factory should be used.

from openobd_protocol.Communication import CommunicationServices_pb2_grpc as grpcCommunicationService
from openobd.core.grpc_factory import GrpcFactory

class MockGrpcFactory(GrpcFactory):
    def __init__(self):
        super().__init__()

    def get_can(self) -> grpcCommunicationService.canStub | grpcCommunicationService.canServicer:
        return CanEchoService()

Using a mock factory

When writing tests, you can create an OpenOBDSession object, configured with the mock grpc service. This allows you to test all openOBD communication with the remote, with the UI and with functions.

Please note that this method is not suitable for testing the creation of an OpenOBDSession object.

from unittest import TestCase
from openobd import *

class TestExample(TestCase):
    def setUp(self):
        super().setUp()
        self.session = OpenOBDSession(grpc_factory=MockGrpcFactory(), session_info=SessionInfo())

def test_echo(self):
    socket = RawSocket(openobd_session = self.session, raw_channel=RawChannel(bus_name="can_6_14_RAW", request_id=0x7E0, response_id=0x7E8))

    # When we send 1003
    socket.send("1003")

    # The result should be 1003 as well
    response = socket.receive()
    self.assertEqual("1003", response)