summaryrefslogtreecommitdiff
path: root/horizon/test/helpers.py
blob: 3c5b21d13ae33a10a5288dc894e689f11e9f79fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging
import os
import socket
import time

from django.contrib.auth.middleware import AuthenticationMiddleware  # noqa
from django.contrib.auth.models import Permission  # noqa
from django.contrib.auth.models import User  # noqa
from django.contrib.contenttypes.models import ContentType  # noqa
from django.contrib.messages.storage import default_storage  # noqa
from django.contrib.sessions.backends.base import SessionBase  # noqa
from django.core.handlers import wsgi
from django import http
from django import test as django_test
from django.test.client import RequestFactory  # noqa
from django.utils.encoding import force_text
from django.utils import unittest

LOG = logging.getLogger(__name__)


try:
    from selenium.webdriver.support import ui as selenium_ui
    import xvfbwrapper  # Only needed when running the Selenium tests headless

    from horizon.test.webdriver import WebDriver  # noqa
except ImportError as e:
    # NOTE(saschpe): Several distribution can't ship selenium due to its
    # non-free license. So they have to patch it out of test-requirements.txt
    # Avoid import failure and force not running selenium tests.
    LOG.warning("{0}, force WITH_SELENIUM=False".format(str(e)))
    os.environ['WITH_SELENIUM'] = ''


import mox

from horizon import middleware


# Makes output of failing mox tests much easier to read.
wsgi.WSGIRequest.__repr__ = lambda self: "<class 'django.http.HttpRequest'>"


class SessionStore(SessionBase):
    """Dict like object for simulating sessions in unittests."""

    def load(self):
        self.create()
        return {}

    def create(self):
        self.modified = True

    def save(self, must_create=False):
        self._session_key = self._get_session_key()
        self.modified = True

    def exists(self, session_key=None):
        return False

    def delete(self, session_key=None):

        self._session_key = ''
        self._session_cache = {}
        self.modified = True

    def cycle_key(self):
        self.save()

    @classmethod
    def clear_expired(cls):
        pass


class RequestFactoryWithMessages(RequestFactory):
    def get(self, *args, **kwargs):
        req = super(RequestFactoryWithMessages, self).get(*args, **kwargs)
        req.user = User()
        req.session = SessionStore()
        req._messages = default_storage(req)
        return req

    def post(self, *args, **kwargs):
        req = super(RequestFactoryWithMessages, self).post(*args, **kwargs)
        req.user = User()
        req.session = SessionStore()
        req._messages = default_storage(req)
        return req


@unittest.skipIf(os.environ.get('SKIP_UNITTESTS', False),
                 "The SKIP_UNITTESTS env variable is set.")
class TestCase(django_test.TestCase):
    """Specialized base test case class for Horizon which gives access to
    numerous additional features:

      * The ``mox`` mocking framework via ``self.mox``.
      * A ``RequestFactory`` class which supports Django's ``contrib.messages``
        framework via ``self.factory``.
      * A ready-to-go request object via ``self.request``.
    """
    def setUp(self):
        self.mox = mox.Mox()
        self.factory = RequestFactoryWithMessages()
        self.user = User.objects.create_user(username='test', password='test')
        self.assertTrue(self.client.login(username="test", password="test"))

        self.request = http.HttpRequest()
        self.request.session = self.client._session()
        middleware.HorizonMiddleware().process_request(self.request)
        AuthenticationMiddleware().process_request(self.request)
        os.environ["HORIZON_TEST_RUN"] = "True"

    def tearDown(self):
        self.mox.UnsetStubs()
        self.mox.VerifyAll()
        del os.environ["HORIZON_TEST_RUN"]

    def set_permissions(self, permissions=None):
        perm_ids = Permission.objects.values_list('id', flat=True)
        self.user.user_permissions.remove(*perm_ids)
        for name in permissions:
            ct, create = ContentType.objects.get_or_create(model=name,
                                                           app_label='horizon')
            perm, create = Permission.objects.get_or_create(codename=name,
                                                            content_type=ct,
                                                            name=name)
            self.user.user_permissions.add(perm)
        if hasattr(self.user, "_perm_cache"):
            del self.user._perm_cache

    def assertNoMessages(self, response=None):
        """Asserts that no messages have been attached by the
        ``contrib.messages`` framework.
        """
        self.assertMessageCount(response, success=0, warn=0, info=0, error=0)

    def assertMessageCount(self, response=None, **kwargs):
        """Asserts that the specified number of messages have been attached
        for various message types. Usage would look like
        ``self.assertMessageCount(success=1)``.
        """
        temp_req = self.client.request(**{'wsgi.input': None})
        temp_req.COOKIES = self.client.cookies
        storage = default_storage(temp_req)
        messages = []

        if response is None:
            # To gain early access to the messages we have to decode the
            # cookie on the test client.
            if 'messages' in self.client.cookies:
                message_cookie = self.client.cookies['messages'].value
                messages = storage._decode(message_cookie)
        # Check for messages in the context
        elif hasattr(response, "context") and "messages" in response.context:
            messages = response.context["messages"]
        # Check for messages attached to the request on a TemplateResponse
        elif hasattr(response, "_request") and hasattr(response._request,
                                                       "_messages"):
            messages = response._request._messages._queued_messages

        # If we don't have messages and we don't expect messages, we're done.
        if not any(kwargs.values()) and not messages:
            return

        # If we expected messages and have none, that's a problem.
        if any(kwargs.values()) and not messages:
            error_msg = "Messages were expected, but none were set."
            assert 0 == sum(kwargs.values()), error_msg

        # Otherwise, make sure we got the expected messages.
        for msg_type, count in kwargs.items():
            msgs = [force_text(m.message)
                    for m in messages if msg_type in m.tags]
            assert len(msgs) == count, \
                "%s messages not as expected: %s" % (msg_type.title(),
                                                     ", ".join(msgs))


@unittest.skipUnless(os.environ.get('WITH_SELENIUM', False),
                     "The WITH_SELENIUM env variable is not set.")
class SeleniumTestCase(django_test.LiveServerTestCase):
    @classmethod
    def setUpClass(cls):
        socket.setdefaulttimeout(60)
        if os.environ.get('WITH_SELENIUM', False):
            time.sleep(1)
            # Start a virtual display server for running the tests headless.
            if os.environ.get('SELENIUM_HEADLESS', False):
                cls.vdisplay = xvfbwrapper.Xvfb(width=1280, height=720)
                cls.vdisplay.start()
            cls.selenium = WebDriver()
        super(SeleniumTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        if os.environ.get('WITH_SELENIUM', False):
            cls.selenium.quit()
            time.sleep(1)
        if hasattr(cls, 'vdisplay'):
            cls.vdisplay.stop()
        super(SeleniumTestCase, cls).tearDownClass()

    def setUp(self):
        socket.setdefaulttimeout(60)
        self.selenium.implicitly_wait(30)
        self.ui = selenium_ui
        super(SeleniumTestCase, self).setUp()


class JasmineTests(SeleniumTestCase):
    """Helper class which allows you to create a simple Jasmine test running
    through Selenium

    To run a jasmine test suite create a class which extends JasmineTests in
    the :file:`horizon/test/jasmine/jasmine_tests.py` and define two class
    attributes

    .. attribute:: sources

        A list of JS source files (the {{STATIC_URL}} will be added
        automatically, these are the source files tested

    .. attribute:: specs

        A list of Jasmine JS spec files (the {{STATIC_URL}} will be added
        automatically

    .. attribute:: template_name

        A template which will contain the html needed by the test,
        this attribute is optional, if it is not specified the default template
        will be used. The template, if specified, must extends
        :file:`horizon/jasmine/jasmine.html` and insert the html in a block
        which name must be content
    """
    sources = []
    specs = []
    template_name = None

    def run_jasmine(self):
        self.selenium.get(
            "%s%s%s" % (self.live_server_url,
                        "/jasmine/",
                        self.__class__.__name__))

        wait = self.ui.WebDriverWait(self.selenium, 120)

        def jasmine_done(driver):
            text = driver.find_element_by_class_name("duration").text
            return "finished" in text

        wait.until(jasmine_done)
        failures = \
            self.selenium.find_elements_by_css_selector(".specDetail.failed")

        results = []
        for failure in failures:
            results.append(
                failure.find_element_by_class_name("description").text)
            results.append(
                failure.find_element_by_class_name("stackTrace").text)

        self.assertEqual(results, [], '\n\n' + '\n\n'.join(results) + '\n\n')

    def test(self):
        if self.__class__ == JasmineTests:
            return
        self.run_jasmine()