1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this
3# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5from marionette_driver.decorators import using_context
6from marionette_driver.errors import MarionetteException
7
8from marionette_harness import MarionetteTestCase
9
10
11class TestSetContext(MarionetteTestCase):
12    def setUp(self):
13        MarionetteTestCase.setUp(self)
14
15        # shortcuts to improve readability of these tests
16        self.chrome = self.marionette.CONTEXT_CHROME
17        self.content = self.marionette.CONTEXT_CONTENT
18
19        test_url = self.marionette.absolute_url("empty.html")
20        self.marionette.navigate(test_url)
21        self.marionette.set_context(self.content)
22        self.assertEquals(self.get_context(), self.content)
23
24    def get_context(self):
25        return self.marionette._send_message("getContext", key="value")
26
27    def test_set_different_context_using_with_block(self):
28        with self.marionette.using_context(self.chrome):
29            self.assertEquals(self.get_context(), self.chrome)
30        self.assertEquals(self.get_context(), self.content)
31
32    def test_set_same_context_using_with_block(self):
33        with self.marionette.using_context(self.content):
34            self.assertEquals(self.get_context(), self.content)
35        self.assertEquals(self.get_context(), self.content)
36
37    def test_nested_with_blocks(self):
38        with self.marionette.using_context(self.chrome):
39            self.assertEquals(self.get_context(), self.chrome)
40            with self.marionette.using_context(self.content):
41                self.assertEquals(self.get_context(), self.content)
42            self.assertEquals(self.get_context(), self.chrome)
43        self.assertEquals(self.get_context(), self.content)
44
45    def test_set_scope_while_in_with_block(self):
46        with self.marionette.using_context(self.chrome):
47            self.assertEquals(self.get_context(), self.chrome)
48            self.marionette.set_context(self.content)
49            self.assertEquals(self.get_context(), self.content)
50        self.assertEquals(self.get_context(), self.content)
51
52    def test_exception_raised_while_in_with_block_is_propagated(self):
53        with self.assertRaises(MarionetteException):
54            with self.marionette.using_context(self.chrome):
55                raise MarionetteException
56        self.assertEquals(self.get_context(), self.content)
57
58    def test_with_using_context_decorator(self):
59        @using_context('content')
60        def inner_content(m):
61            self.assertEquals(self.get_context(), 'content')
62        @using_context('chrome')
63        def inner_chrome(m):
64            self.assertEquals(self.get_context(), 'chrome')
65        inner_content(self.marionette)
66        inner_chrome(self.marionette)
67