test_protocol.py 1.25 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
Deshui Yu's avatar
Deshui Yu committed
3

4
5
from nni.runtime import protocol
from nni.runtime.protocol import CommandType, send, receive
Deshui Yu's avatar
Deshui Yu committed
6
7
8
9
10
11

from io import BytesIO
from unittest import TestCase, main


def _prepare_send():
12
13
    protocol._out_file = BytesIO()
    return protocol._out_file
Deshui Yu's avatar
Deshui Yu committed
14
15

def _prepare_receive(data):
16
    protocol._in_file = BytesIO(data)
Deshui Yu's avatar
Deshui Yu committed
17
18
19
20
21
22


class ProtocolTestCase(TestCase):
    def test_send_en(self):
        out_file = _prepare_send()
        send(CommandType.NewTrialJob, 'CONTENT')
23
        self.assertEqual(out_file.getvalue(), b'TR00000000000007CONTENT')
Deshui Yu's avatar
Deshui Yu committed
24
25
26
27

    def test_send_zh(self):
        out_file = _prepare_send()
        send(CommandType.NewTrialJob, '你好')
28
        self.assertEqual(out_file.getvalue(), 'TR00000000000006你好'.encode('utf8'))
Deshui Yu's avatar
Deshui Yu committed
29
30

    def test_receive_en(self):
31
        _prepare_receive(b'IN00000000000005hello')
Deshui Yu's avatar
Deshui Yu committed
32
33
34
35
36
        command, data = receive()
        self.assertIs(command, CommandType.Initialize)
        self.assertEqual(data, 'hello')

    def test_receive_zh(self):
37
        _prepare_receive('IN00000000000006世界'.encode('utf8'))
Deshui Yu's avatar
Deshui Yu committed
38
39
40
41
42
43
44
        command, data = receive()
        self.assertIs(command, CommandType.Initialize)
        self.assertEqual(data, '世界')


if __name__ == '__main__':
    main()