Move tests: unit/apiserver/
[yardstick.git] / yardstick / tests / unit / apiserver / __init__.py
1 ##############################################################################
2 # Copyright (c) 2017
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 """Tests for yardstick/api/server.py"""
10 from __future__ import absolute_import
11
12 import mock
13 import os
14 import socket
15 import unittest
16 import tempfile
17
18 from oslo_serialization import jsonutils
19
20 from yardstick.common import constants as consts
21
22
23 class APITestCase(unittest.TestCase):
24     """Tests for the YardStick API server"""
25     def setUp(self):
26         self.db_fd, self.db_path = tempfile.mkstemp()
27         consts.SQLITE = 'sqlite:///{}'.format(self.db_path)
28
29         # server calls gethostbyname which takes 4 seconds, and we should mock
30         # it anyway
31         self.socket_mock = mock.patch.dict("sys.modules", {"socket": mock.MagicMock(
32             **{"gethostbyname.return_value": "127.0.0.1",
33                "gethostname.return_value": "localhost"})})
34         self.socket_mock.start()
35         try:
36             from api import server
37         except socket.gaierror:
38             self.app = None
39             return
40
41         server.app.config['TESTING'] = True
42         self.app = server.app.test_client()
43
44         server.init_db()
45
46     def tearDown(self):
47         os.close(self.db_fd)
48         os.unlink(self.db_path)
49         self.socket_mock.stop()
50
51     def _post(self, url, data):
52         headers = {'Content-Type': 'application/json'}
53         resp = self.app.post(url, data=jsonutils.dumps(data), headers=headers)
54         return jsonutils.loads(resp.data)
55
56     def _get(self, url):
57         resp = self.app.get(url)
58         return jsonutils.loads(resp.data)