test_word_cloud.py 8.66 KB
Newer Older
1 2 3 4 5
# -*- coding: utf-8 -*-
"""Word cloud integration tests using mongo modulestore."""

import json
from operator import itemgetter
6

7
from nose.plugins.attrib import attr
8

9
from xmodule.x_module import STUDENT_VIEW
10

11
from .helpers import BaseTestXmodule
12

13

14
@attr(shard=1)
15 16 17 18
class TestWordCloud(BaseTestXmodule):
    """Integration test for word cloud xmodule."""
    CATEGORY = "word_cloud"

19
    def _get_resource_url(self, item):
Toby Lawrence committed
20 21 22
        """
        Creates a resource URL for a given asset that is compatible with this old XModule testing stuff.
        """
23
        display_name = self.item_descriptor.display_name.replace(' ', '_')
Toby Lawrence committed
24 25 26
        return "resource/i4x://{}/{}/word_cloud/{}/{}".format(
            self.course.id.org, self.course.id.course, display_name, item
        )
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
    def _get_users_state(self):
        """Return current state for each user:

        {username: json_state}
        """
        # check word cloud response for every user
        users_state = {}

        for user in self.users:
            response = self.clients[user.username].post(self.get_url('get_state'))
            users_state[user.username] = json.loads(response.content)

        return users_state

    def _post_words(self, words):
        """Post `words` and return current state for each user:

        {username: json_state}
        """
        users_state = {}

        for user in self.users:
            response = self.clients[user.username].post(
                self.get_url('submit'),
                {'student_words[]': words},
                HTTP_X_REQUESTED_WITH='XMLHttpRequest'
            )
            users_state[user.username] = json.loads(response.content)

        return users_state

    def _check_response(self, response_contents, correct_jsons):
        """Utility function that compares correct and real responses."""
        for username, content in response_contents.items():

            # Used in debugger for comparing objects.
            # self.maxDiff = None

            # We should compare top_words for manually,
            # because they are unsorted.
            keys_to_compare = set(content.keys()).difference(set(['top_words']))
            self.assertDictEqual(
                {k: content[k] for k in keys_to_compare},
                {k: correct_jsons[username][k] for k in keys_to_compare})

            # comparing top_words:
            top_words_content = sorted(
                content['top_words'],
                key=itemgetter('text')
            )
            top_words_correct = sorted(
                correct_jsons[username]['top_words'],
                key=itemgetter('text')
            )
            self.assertListEqual(top_words_content, top_words_correct)

    def test_initial_state(self):
        """Inital state of word cloud is correct. Those state that
        is sended from server to frontend, when students load word
        cloud page.
        """
        users_state = self._get_users_state()

        self.assertEqual(
            ''.join(set([
                        content['status']
                        for _, content in users_state.items()
                        ])),
            'success')

        # correct initial data:
        correct_initial_data = {
            u'status': u'success',
            u'student_words': {},
            u'total_count': 0,
            u'submitted': False,
            u'top_words': {},
            u'display_student_percents': False
        }

        for _, response_content in users_state.items():
            self.assertEquals(response_content, correct_initial_data)

    def test_post_words(self):
        """Students can submit data succesfully.
        Word cloud data properly updates after students submit.
        """
        input_words = [
            "small",
            "BIG",
            " Spaced ",
            " few words",
        ]

        correct_words = [
            u"small",
            u"big",
            u"spaced",
            u"few words",
        ]

        users_state = self._post_words(input_words)

        self.assertEqual(
            ''.join(set([
                        content['status']
                        for _, content in users_state.items()
                        ])),
            'success')

        correct_state = {}
        for index, user in enumerate(self.users):

            correct_state[user.username] = {
                u'status': u'success',
                u'submitted': True,
                u'display_student_percents': True,
                u'student_words': {word: 1 + index for word in correct_words},
                u'total_count': len(input_words) * (1 + index),
                u'top_words': [
                    {
                        u'text': word, u'percent': 100 / len(input_words),
                        u'size': (1 + index)
                    }
                    for word in correct_words
                ]
            }

        self._check_response(users_state, correct_state)

    def test_collective_users_submits(self):
        """Test word cloud data flow per single and collective users submits.

            Make sures that:

            1. Inital state of word cloud is correct. Those state that
            is sended from server to frontend, when students load word
            cloud page.

            2. Students can submit data succesfully.

            3. Next submits produce "already voted" error. Next submits for user
            are not allowed by user interface, but techically it possible, and
            word_cloud should properly react.

            4. State of word cloud after #3 is still as after #2.
        """

        # 1.
        users_state = self._get_users_state()

        self.assertEqual(
            ''.join(set([
                        content['status']
                        for _, content in users_state.items()
                        ])),
            'success')

        # 2.
        # Invcemental state per user.
        users_state_after_post = self._post_words(['word1', 'word2'])

        self.assertEqual(
            ''.join(set([
                        content['status']
                        for _, content in users_state_after_post.items()
                        ])),
            'success')

        # Final state after all posts.
        users_state_before_fail = self._get_users_state()

        # 3.
        users_state_after_post = self._post_words(
            ['word1', 'word2', 'word3'])

        self.assertEqual(
            ''.join(set([
                        content['status']
                        for _, content in users_state_after_post.items()
                        ])),
            'fail')

        # 4.
        current_users_state = self._get_users_state()
        self._check_response(users_state_before_fail, current_users_state)

    def test_unicode(self):
        input_words = [u" this is unicode Юникод"]
        correct_words = [u"this is unicode юникод"]

        users_state = self._post_words(input_words)

        self.assertEqual(
            ''.join(set([
                        content['status']
                        for _, content in users_state.items()
                        ])),
            'success')

        for user in self.users:
            self.assertListEqual(
                users_state[user.username]['student_words'].keys(),
                correct_words)

    def test_handle_ajax_incorrect_dispatch(self):
        responses = {
            user.username: self.clients[user.username].post(
                self.get_url('whatever'),
                {},
                HTTP_X_REQUESTED_WITH='XMLHttpRequest')
            for user in self.users
        }

David Baumgold committed
242 243
        status_codes = {response.status_code for response in responses.values()}
        self.assertEqual(status_codes.pop(), 200)
244 245 246 247 248 249 250

        for user in self.users:
            self.assertDictEqual(
                json.loads(responses[user.username].content),
                {
                    'status': 'fail',
                    'error': 'Unknown Command!'
David Baumgold committed
251 252
                }
            )
253 254

    def test_word_cloud_constructor(self):
255 256 257
        """
        Make sure that all parameters extracted correctly from xml.
        """
258
        fragment = self.runtime.render(self.item_descriptor, STUDENT_VIEW)
259
        expected_context = {
260
            'ajax_url': self.item_descriptor.xmodule_runtime.ajax_url,
261 262
            'display_name': self.item_descriptor.display_name,
            'instructions': self.item_descriptor.instructions,
263 264
            'element_class': self.item_descriptor.location.category,
            'element_id': self.item_descriptor.location.html_id(),
265
            'num_inputs': 5,  # default value
266
            'submitted': False,  # default value,
267
        }
268

269
        self.assertEqual(fragment.content, self.runtime.render_template('word_cloud.html', expected_context))