1#! /usr/bin/python 2 3# Copyright 2014 The Chromium OS Authors. All rights reserved. 4# Use of this source code is governed by a BSD-style license that can be 5# found in the LICENSE file. 6 7"""Unit tests for common_util methods.""" 8 9import cherrypy 10import json 11import tempfile 12import unittest 13 14import common 15from fake_device_server import common_util 16from fake_device_server import server_errors 17 18 19class FakeDeviceServerTests(unittest.TestCase): 20 """Contains tests for methods not included in classes.""" 21 22 def testParseSerializeJson(self): 23 """Tests that we can seralize / deserialize json from cherrypy.""" 24 json_data = json.dumps(dict(a='b', b='c')) 25 26 json_file = tempfile.TemporaryFile() 27 json_file.write(json.dumps(json_data)) 28 content_length = json_file.tell() 29 json_file.seek(0) 30 cherrypy.request.headers['Content-Length'] = content_length 31 32 cherrypy.request.rfile = json_file 33 34 self.assertEquals(common_util.parse_serialized_json(), json_data) 35 json_file.close() 36 37 # Also test the edge case without an input file. 38 json_file = tempfile.TemporaryFile() 39 cherrypy.request.rfile = json_file 40 41 self.assertEquals(common_util.parse_serialized_json(), None) 42 json_file.close() 43 44 45 def testParseCommonArgs(self): 46 """Tests various flavors of the parse common args method.""" 47 id = 123456 48 key = 'boogity' 49 50 # Should parse all values. 51 id, api_key, op = common_util.parse_common_args( 52 (id, 'boogity',), 53 dict(key=key), supported_operations=set(['boogity'])) 54 self.assertEquals(id, id) 55 self.assertEquals(key, api_key) 56 self.assertEquals('boogity', op) 57 58 # Missing op. 59 id, api_key, op = common_util.parse_common_args((id,), dict(key=key)) 60 self.assertEquals(id, id) 61 self.assertEquals(key, api_key) 62 self.assertIsNone(op) 63 64 # Missing key. 65 id, api_key, op = common_util.parse_common_args((id,), dict()) 66 self.assertEquals(id, id) 67 self.assertIsNone(api_key) 68 self.assertIsNone(op) 69 70 # Missing all. 71 id, api_key, op = common_util.parse_common_args(tuple(), dict()) 72 self.assertIsNone(id) 73 self.assertIsNone(api_key) 74 self.assertIsNone(op) 75 76 # Too many args. 77 self.assertRaises(server_errors.HTTPError, 78 common_util.parse_common_args, 79 (id, 'lame', 'stuff',), dict()) 80 81 # Operation when it's not expected. 82 self.assertRaises(server_errors.HTTPError, 83 common_util.parse_common_args, 84 (id, 'boogity'), dict()) 85 86 87if __name__ == '__main__': 88 unittest.main() 89