Best Python code snippet using playwright-python
test_pydermonkey.py
Source:test_pydermonkey.py
...13 self.last_exception = None14 while self._teardowns:15 obj = self._teardowns.pop()16 runtime = obj.get_runtime()17 runtime.new_context().clear_object_private(obj)18 del runtime19 del obj20 self.assertEqual(pydermonkey.get_debug_info()['runtime_count'], 0)21 def _clearOnTeardown(self, obj):22 self._teardowns.append(obj)23 def _evaljs(self, code, cx=None, obj=None):24 if cx is None:25 rt = pydermonkey.Runtime()26 cx = rt.new_context()27 if obj is None:28 obj = cx.new_object()29 cx.init_standard_classes(obj)30 return cx.evaluate_script(obj, code, '<string>', 1)31 def _execjs(self, code):32 rt = pydermonkey.Runtime()33 cx = rt.new_context()34 obj = cx.new_object()35 cx.init_standard_classes(obj)36 script = cx.compile_script(code, '<string>', 1)37 return cx.execute_script(obj, script)38 def _evalJsWrappedPyFunc(self, func, code):39 cx = pydermonkey.Runtime().new_context()40 obj = cx.new_object()41 cx.init_standard_classes(obj)42 jsfunc = cx.new_function(func, func.__name__)43 self._clearOnTeardown(jsfunc)44 cx.define_property(obj, func.__name__, jsfunc)45 return cx.evaluate_script(obj, code, '<string>', 1)46 def assertRaises(self, exctype, func, *args):47 was_raised = False48 try:49 func(*args)50 except exctype, e:51 self.last_exception = e52 was_raised = True53 self.assertTrue(was_raised)54 def testVersionIsCorrect(self):55 # Really hackish way of importing values from metadata.py.56 import os57 mydir = os.path.dirname(__file__)58 rootdir = os.path.join(mydir, '..')59 rootdir = os.path.normpath(rootdir)60 sys.path.insert(0, rootdir)61 import metadata62 self.assertEqual(pydermonkey.__version__, metadata.VERSION)63 def testDeletePropertyWorks(self):64 cx = pydermonkey.Runtime().new_context()65 obj = cx.new_object()66 cx.define_property(obj, 'foo', 1)67 self.assertEqual(cx.delete_property(obj, 'foo'), True)68 self.assertEqual(cx.delete_property(obj, 'foo'), True)69 self.assertEqual(cx.get_property(obj, 'foo'),70 pydermonkey.undefined)71 def testSetPropertyWorks(self):72 cx = pydermonkey.Runtime().new_context()73 obj = cx.new_object()74 self.assertEqual(cx.set_property(obj, 'blah', 5), 5)75 self.assertEqual(cx.set_property(obj, 3, 2), 2)76 self.assertEqual(cx.set_property(obj, u'blah\u2026', 5), 5)77 self.assertEqual(cx.get_property(obj, 3), 2)78 def testSetPropertyReturnsDifferentValue(self):79 cx = pydermonkey.Runtime().new_context()80 obj = cx.new_object()81 cx.init_standard_classes(obj)82 o2 = self._evaljs("({set blah() { return 5; }})", cx, obj)83 self.assertEqual(cx.set_property(o2, 'blah', 3), 5)84 def testSetPropertyRaisesExceptionOnReadOnly(self):85 cx = pydermonkey.Runtime().new_context()86 obj = cx.new_object()87 cx.init_standard_classes(obj)88 o2 = self._evaljs("({get blah() { return 5; }})", cx, obj)89 self.assertRaises(90 # TODO: Shouldn't this be a ScriptError?91 pydermonkey.InterpreterError,92 cx.set_property,93 o2, 'blah', 394 )95 self.assertEqual(self.last_exception.args[0],96 "setting a property that has only a getter")97 def testDefinePropertyRaisesNoExceptionOnReadOnly(self):98 cx = pydermonkey.Runtime().new_context()99 obj = cx.new_object()100 cx.init_standard_classes(obj)101 o2 = self._evaljs("({get blah() { return 5; }})", cx, obj)102 cx.define_property(o2, 'blah', 3)103 self.assertEqual(cx.get_property(o2, 'blah'), 3)104 def testLookupPropertyWorks(self):105 cx = pydermonkey.Runtime().new_context()106 obj = cx.new_object()107 cx.init_standard_classes(obj)108 o2 = self._evaljs("({foo: 1, get blah() { return 5; }})", cx, obj)109 self.assertEqual(cx.lookup_property(o2, 'bar'),110 pydermonkey.undefined)111 self.assertEqual(cx.lookup_property(o2, 'foo'), 1)112 self.assertEqual(cx.lookup_property(o2, 'blah'), True)113 self.assertEqual(cx.get_property(o2, 'blah'), 5)114 self.assertEqual(cx.lookup_property(o2, 'blah'), True)115 def testSyntaxErrorsAreRaised(self):116 for run in [self._evaljs, self._execjs]:117 self.assertRaises(pydermonkey.ScriptError, run, '5f')118 self.assertEqual(119 self.last_exception.args[1],120 u'SyntaxError: missing ; before statement'121 )122 def testGetStackOnEmptyStackReturnsNone(self):123 cx = pydermonkey.Runtime().new_context()124 self.assertEqual(cx.get_stack(), None)125 def testGetStackWorks(self):126 stack_holder = []127 def func(cx, this, args):128 stack_holder.append(cx.get_stack())129 cx = pydermonkey.Runtime().new_context()130 obj = cx.new_object()131 cx.init_standard_classes(obj)132 jsfunc = cx.new_function(func, func.__name__)133 self._clearOnTeardown(jsfunc)134 cx.define_property(obj, func.__name__, jsfunc)135 cx.evaluate_script(obj, '(function closure() { \nfunc() })()',136 '<string>', 1)137 stack = stack_holder[0]138 script = stack['caller']['caller']['script']139 pc = stack['caller']['caller']['pc']140 closure = stack['caller']['function']141 self.assertEqual(closure.name, 'closure')142 self.assertEqual(closure.filename, '<string>')143 self.assertEqual(stack['caller']['script'], None)144 self.assertEqual(stack['caller']['lineno'], 2)145 self.assertEqual(script.filename, '<string>')146 self.assertEqual(stack['caller']['caller']['lineno'], 1)147 self.assertTrue(pc >= 0 and pc < len(buffer(script)))148 self.assertEqual(stack['caller']['caller']['caller'], None)149 def testNewObjectTakesProto(self):150 cx = pydermonkey.Runtime().new_context()151 obj = cx.new_object()152 cx.define_property(obj, 5, "foo")153 obj2 = cx.new_object(None, obj)154 self.assertEqual(cx.get_property(obj2, 5), "foo")155 def testInitStandardClassesWorksTwice(self):156 cx = pydermonkey.Runtime().new_context()157 obj = cx.new_object()158 cx.init_standard_classes(obj)159 obj2 = cx.new_object()160 # TODO: This is really just a workaround for issue #3:161 # http://code.google.com/p/pydermonkey/issues/detail?id=3162 self.assertRaises(163 pydermonkey.InterpreterError,164 cx.init_standard_classes,165 obj2166 )167 self.assertEqual(168 self.last_exception.args[0],169 "Can't init standard classes on the same context twice."170 ) 171 def testNewArrayObjectWorks(self):172 cx = pydermonkey.Runtime().new_context()173 array = cx.new_array_object()174 self.assertTrue(cx.is_array_object(array))175 def testIsArrayWorks(self):176 cx = pydermonkey.Runtime().new_context()177 obj = cx.new_object()178 self.assertFalse(cx.is_array_object(obj))179 array = cx.evaluate_script(obj, '[1]', '<string>', 1)180 self.assertTrue(cx.is_array_object(array))181 def testEnumerateWorks(self):182 cx = pydermonkey.Runtime().new_context()183 obj = cx.new_object()184 cx.evaluate_script(obj, "var blah = 1; var foo = 2; this[0] = 5;",185 "<string>", 1)186 self.assertEqual(cx.enumerate(obj), ("blah", "foo", 0))187 def testBigArrayIndicesRaiseValueError(self):188 cx = pydermonkey.Runtime().new_context()189 obj = cx.new_object()190 self.assertRaises(191 ValueError,192 cx.define_property,193 obj, 2 ** 30, 'foo' # Should be a PyInt object.194 )195 self.assertEqual(self.last_exception.args[0],196 "Integer property value out of range.")197 def testReallyBigArrayIndicesRaiseValueError(self):198 cx = pydermonkey.Runtime().new_context()199 obj = cx.new_object()200 self.assertRaises(201 ValueError,202 cx.define_property,203 obj, sys.maxint + 1, 'foo' # Should be a PyLong object.204 )205 self.assertEqual(self.last_exception.args[0],206 "Integer property value out of range.")207 def testScriptHasFilenameMember(self):208 cx = pydermonkey.Runtime().new_context()209 script = cx.compile_script('foo', '<string>', 1)210 self.assertEqual(script.filename, '<string>')211 def testScriptHasLineInfo(self):212 cx = pydermonkey.Runtime().new_context()213 script = cx.compile_script('foo\nbar', '<string>', 1)214 self.assertEqual(script.base_lineno, 1)215 self.assertEqual(script.line_extent, 2)216 def testScriptIsExposedAsBuffer(self):217 rt = pydermonkey.Runtime()218 cx = rt.new_context()219 script = cx.compile_script('foo', '<string>', 1)220 self.assertTrue(len(buffer(script)) > 0)221 def testCompileScriptWorks(self):222 self.assertEqual(self._execjs('5 + 1'), 6)223 def testErrorsRaisedIncludeStrings(self):224 self.assertRaises(pydermonkey.ScriptError, self._evaljs, 'boop()')225 self.assertEqual(self.last_exception.args[1],226 u'ReferenceError: boop is not defined')227 def testThreadSafetyExceptionIsRaised(self):228 stuff = {}229 def make_runtime():230 stuff['rt'] = pydermonkey.Runtime()231 thread = threading.Thread(target = make_runtime)232 thread.start()233 thread.join()234 self.assertRaises(pydermonkey.InterpreterError,235 stuff['rt'].new_context)236 self.assertEqual(self.last_exception.args[0],237 'Function called from wrong thread')238 del stuff['rt']239 def testClearObjectPrivateWorks(self):240 class Foo(object):241 pass242 pyobj = Foo()243 cx = pydermonkey.Runtime().new_context()244 obj = cx.new_object(pyobj)245 pyobj = weakref.ref(pyobj)246 self.assertEqual(pyobj(), cx.get_object_private(obj))247 cx.clear_object_private(obj)248 self.assertEqual(cx.get_object_private(obj), None)249 self.assertEqual(pyobj(), None)250 def testGetObjectPrivateWorks(self):251 class Foo(object):252 pass253 pyobj = Foo()254 cx = pydermonkey.Runtime().new_context()255 obj = cx.new_object(pyobj)256 pyobj = weakref.ref(pyobj)257 self.assertEqual(pyobj(), cx.get_object_private(obj))258 del obj259 del cx260 self.assertEqual(pyobj(), None)261 def testContextSupportsCyclicGc(self):262 def makecx():263 cx = pydermonkey.Runtime().new_context()264 def opcb(othercx):265 return cx266 cx.set_operation_callback(opcb)267 return cx268 gc.disable()269 cx = makecx()270 wcx = weakref.ref(cx)271 self.assertEqual(wcx(), cx)272 del cx273 self.assertTrue(wcx())274 gc.enable()275 gc.collect()276 self.assertEqual(wcx(), None)277 def testKeyboardInterruptStopsScript(self):278 # Let's be super-evil and have multiple interleavings of the JS279 # stack with the Python stack.280 def opcb(cx):281 raise Exception('hello')282 cx = pydermonkey.Runtime().new_context()283 cx.set_operation_callback(opcb)284 obj = cx.new_object()285 cx.init_standard_classes(obj)286 passthrus = []287 def func(cx, this, args):288 try:289 cx.evaluate_script(290 this,291 'try { while (1) {} } catch (e) {}',292 '<string>', 1293 )294 except Exception, e:295 passthrus.append(e)296 raise297 cx.define_property(obj,298 'func',299 cx.new_function(func, 'func'))300 def watchdog():301 time.sleep(0.1)302 cx.trigger_operation_callback()303 thread = threading.Thread(target = watchdog)304 thread.start()305 self.assertRaises(306 Exception,307 cx.evaluate_script,308 obj, 'while (1) { func(); }', '<string>', 1309 )310 self.assertEqual(len(passthrus), 1)311 self.assertEqual(self.last_exception, passthrus[0])312 self.assertEqual(self.last_exception.args[0], 'hello')313 def testOperationCallbackIsCalled(self):314 def opcb(cx):315 raise Exception("stop eet!")316 cx = pydermonkey.Runtime().new_context()317 cx.set_operation_callback(opcb)318 obj = cx.new_object()319 cx.init_standard_classes(obj)320 def watchdog():321 time.sleep(0.1)322 cx.trigger_operation_callback()323 thread = threading.Thread(target = watchdog)324 thread.start()325 self.assertRaises(326 Exception,327 cx.evaluate_script,328 obj, 'while (1) {}', '<string>', 1329 )330 self.assertEqual(self.last_exception.args[0],331 'stop eet!')332 def testUndefinedStrIsUndefined(self):333 self.assertEqual(str(pydermonkey.undefined),334 "pydermonkey.undefined")335 def testScriptedJsFuncHasIsPythonFalse(self):336 cx = pydermonkey.Runtime().new_context()337 jsfunc = cx.evaluate_script(cx.new_object(), 338 '(function(){})', '<string>', 1)339 self.assertFalse(jsfunc.is_python)340 def testRecreatedJsWrappedPythonFuncHasIsPythonTrue(self):341 def foo(cx, this, args):342 pass343 cx = pydermonkey.Runtime().new_context()344 obj = cx.new_object()345 cx.define_property(obj, 'foo',346 cx.new_function(foo, foo.__name__))347 self.assertTrue(cx.get_property(obj, 'foo').is_python)348 def testJsWrappedPythonFuncHasIsPythonTrue(self):349 def foo(cx, this, args):350 pass351 cx = pydermonkey.Runtime().new_context()352 jsfunc = cx.new_function(foo, foo.__name__)353 self.assertTrue(jsfunc.is_python)354 def testJsWrappedPythonFuncHasNoFilename(self):355 def foo(cx, this, args):356 pass357 cx = pydermonkey.Runtime().new_context()358 jsfunc = cx.new_function(foo, foo.__name__)359 self.assertEqual(jsfunc.filename, None)360 def testJsScriptedFuncHasNoPrivate(self):361 cx = pydermonkey.Runtime().new_context()362 jsfunc = cx.evaluate_script(cx.new_object(),363 '(function(){})', '<string>', 1)364 self.assertEqual(cx.get_object_private(jsfunc), None)365 def testGetPendingExceptionReturnsNone(self):366 cx = pydermonkey.Runtime().new_context()367 self.assertFalse(cx.is_exception_pending())368 self.assertEqual(cx.get_pending_exception(), None)369 def testThrowHookWorks(self):370 exceptions = []371 def throwhook(cx):372 self.assertTrue(cx.is_exception_pending())373 exceptions.append(cx.get_pending_exception())374 cx = pydermonkey.Runtime().new_context()375 cx.set_throw_hook(throwhook)376 self.assertRaises(377 pydermonkey.ScriptError,378 cx.evaluate_script,379 cx.new_object(),380 '(function() { throw "hi"; })()',381 '<string>', 1382 )383 self.assertEqual(exceptions, ['hi', 'hi'])384 self.assertFalse(cx.is_exception_pending())385 self.assertEqual(cx.get_pending_exception(), None)386 def testJsWrappedPythonFuncHasPrivate(self):387 def foo(cx, this, args):388 pass389 cx = pydermonkey.Runtime().new_context()390 jsfunc = cx.new_function(foo, foo.__name__)391 self.assertEqual(cx.get_object_private(jsfunc), foo)392 def testJsWrappedPythonFuncIsNotGCd(self):393 def define(cx, obj):394 def func(cx, this, args):395 return u'func was called'396 jsfunc = cx.new_function(func, func.__name__)397 cx.define_property(obj, func.__name__, jsfunc)398 return weakref.ref(func)399 rt = pydermonkey.Runtime()400 cx = rt.new_context()401 obj = cx.new_object()402 cx.init_standard_classes(obj)403 ref = define(cx, obj)404 cx.gc()405 self.assertNotEqual(ref(), None)406 result = cx.evaluate_script(obj, 'func()', '<string>', 1)407 self.assertEqual(result, u'func was called')408 # Now ensure that the wrapped function is GC'd when it's409 # no longer reachable from JS space.410 cx.define_property(obj, 'func', 0)411 cx.gc()412 self.assertEqual(ref(), None)413 def testCircularJsWrappedPythonFuncIsGCdIfPrivateCleared(self):414 def define(cx, obj):415 rt = cx.get_runtime()416 def func(cx, this, args):417 # Oh noes, a circular reference is born!418 rt419 jsfunc = cx.new_function(func, func.__name__)420 cx.define_property(obj, func.__name__, jsfunc)421 return (jsfunc, weakref.ref(func))422 rt = pydermonkey.Runtime()423 cx = rt.new_context()424 obj = cx.new_object()425 cx.init_standard_classes(obj)426 jsfunc, ref = define(cx, obj)427 # This will break the circular reference.428 cx.clear_object_private(jsfunc)429 del jsfunc430 del rt431 del cx432 del obj433 self.assertEqual(ref(), None)434 def testFunctionsWithClosuresAreNotIdentical(self):435 cx = pydermonkey.Runtime().new_context()436 obj = cx.new_object()437 cx.init_standard_classes(obj)438 cx.evaluate_script(439 obj, "function build(x) { return function foo() { return x; } }",440 "<string>", 1441 )442 func1 = cx.evaluate_script(obj, "build(1)", "<string>", 1)443 func2 = cx.evaluate_script(obj, "build(2)", "<string>", 1)444 self.assertNotEqual(func1, func2)445 self.assertEqual(func1.name, 'foo')446 self.assertEqual(func1.name, func2.name)447 def testAnonymousJsFunctionHasNullNameAttribute(self):448 cx = pydermonkey.Runtime().new_context()449 obj = cx.new_object()450 cx.init_standard_classes(obj)451 jsfunc = cx.evaluate_script(obj, "(function() {})",452 "<string>", 1)453 self.assertEqual(jsfunc.name, None)454 def testJsFunctionHasNameAttribute(self):455 cx = pydermonkey.Runtime().new_context()456 obj = cx.new_object()457 cx.init_standard_classes(obj)458 jsfunc = cx.evaluate_script(obj, "(function blarg() {})",459 "<string>", 1)460 self.assertEqual(jsfunc.name, "blarg")461 def testJsWrappedPythonFuncHasNameAttribute(self):462 def func(cx, this, args):463 return True464 cx = pydermonkey.Runtime().new_context()465 jsfunc = cx.new_function(func, "foo")466 self.assertEqual(jsfunc.name, "foo")467 def testJsWrappedPythonFuncIsGCdAtRuntimeDestruction(self):468 def define(cx, obj):469 def func(cx, this, args):470 return u'func was called'471 jsfunc = cx.new_function(func, func.__name__)472 cx.define_property(obj, func.__name__, jsfunc)473 return weakref.ref(func)474 rt = pydermonkey.Runtime()475 cx = rt.new_context()476 obj = cx.new_object()477 cx.init_standard_classes(obj)478 ref = define(cx, obj)479 del rt480 del cx481 del obj482 self.assertEqual(ref(), None)483 def testJsWrappedPythonFuncThrowsExcIfPrivateCleared(self):484 def func(cx, this, args):485 return True486 code = "func()"487 cx = pydermonkey.Runtime().new_context()488 obj = cx.new_object()489 cx.init_standard_classes(obj)490 jsfunc = cx.new_function(func, func.__name__)491 cx.define_property(obj, func.__name__, jsfunc)492 cx.clear_object_private(jsfunc)493 # TODO: Shouldn't this be an InternalError?494 self.assertRaises(pydermonkey.ScriptError,495 cx.evaluate_script,496 obj, code, '<string>', 1)497 self.assertEqual(498 self._tostring(cx, self.last_exception.args[0]),499 "Error: Wrapped Python function no longer exists"500 )501 def testJsWrappedPythonFuncPassesContext(self):502 contexts = []503 def func(cx, this, args):504 contexts.append(cx)505 return True506 code = "func()"507 cx = pydermonkey.Runtime().new_context()508 obj = cx.new_object()509 cx.init_standard_classes(obj)510 jsfunc = cx.new_function(func, func.__name__)511 self._clearOnTeardown(jsfunc)512 cx.define_property(obj, func.__name__, jsfunc)513 cx.evaluate_script(obj, code, '<string>', 1)514 self.assertEqual(contexts[0], cx)515 def testJsWrappedPythonFuncPassesThisArg(self):516 thisObjs = []517 def func(cx, this, args):518 thisObjs.append(this)519 return True520 code = "func()"521 cx = pydermonkey.Runtime().new_context()522 obj = cx.new_object()523 cx.init_standard_classes(obj)524 jsfunc = cx.new_function(func, func.__name__)525 self._clearOnTeardown(jsfunc)526 cx.define_property(obj, func.__name__, jsfunc)527 cx.evaluate_script(obj, code, '<string>', 1)528 self.assertEqual(thisObjs[0], obj)529 def testJsWrappedPythonFuncPassesFuncArgs(self):530 funcArgs = []531 def func(cx, this, args):532 funcArgs.append(args)533 return True534 cx = pydermonkey.Runtime().new_context()535 obj = cx.new_object()536 cx.init_standard_classes(obj)537 jsfunc = cx.new_function(func, func.__name__)538 self._clearOnTeardown(jsfunc)539 cx.define_property(obj, func.__name__, jsfunc)540 cx.evaluate_script(obj, "func()", '<string>', 1)541 self.assertEqual(len(funcArgs[0]), 0)542 self.assertTrue(isinstance(funcArgs[0], tuple))543 cx.evaluate_script(obj, "func(1, 'foo')", '<string>', 1)544 self.assertEqual(len(funcArgs[1]), 2)545 self.assertEqual(funcArgs[1][0], 1)546 self.assertEqual(funcArgs[1][1], u'foo')547 def testJsWrappedPythonFunctionReturnsUnicodeWithEmbeddedNULs(self):548 def hai2u(cx, this, args):549 return args[0] + u"o hai"550 self.assertEqual(self._evalJsWrappedPyFunc(hai2u,551 'hai2u("blah\x00 ")'),552 u"blah\x00 o hai")553 def testJsWrappedPythonFunctionReturnsUndefined(self):554 def hai2u(cx, this, args):555 return pydermonkey.undefined556 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),557 pydermonkey.undefined)558 def testJsWrappedPythonFunctionReturnsString(self):559 def hai2u(cx, this, args):560 return "o hai"561 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),562 "o hai")563 def testJsWrappedPythonFunctionReturnsUnicode(self):564 def hai2u(cx, this, args):565 return u"o hai\u2026"566 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),567 u"o hai\u2026")568 def testJsWrappedPythonFunctionThrowsJsException(self):569 def hai2u(cx, this, args):570 raise pydermonkey.ScriptError(u"blarg")571 self.assertRaises(pydermonkey.ScriptError,572 self._evalJsWrappedPyFunc,573 hai2u, 'hai2u()')574 self.assertEqual(self.last_exception.args[0], u"blarg")575 def testJsWrappedPythonFunctionThrowsJsException2(self):576 def hai2u(cx, this, args):577 cx.evaluate_script(this, 'throw "blarg"', '<string>', 1)578 self.assertRaises(pydermonkey.ScriptError,579 self._evalJsWrappedPyFunc,580 hai2u, 'hai2u()')581 self.assertEqual(self.last_exception.args[0], u"blarg")582 def testJsWrappedPythonFunctionThrowsPyException(self):583 def hai2u(cx, this, args):584 raise Exception("hello")585 self.assertRaises(Exception,586 self._evalJsWrappedPyFunc,587 hai2u, 'hai2u()')588 self.assertEqual(self.last_exception.args[0], "hello")589 def testJsWrappedPythonFunctionThrowsUncatchablePyException(self):590 def hai2u(cx, this, args):591 raise Exception("hello")592 self.assertRaises(Exception,593 self._evalJsWrappedPyFunc,594 hai2u, 'try { hai2u() } catch (e) {}')595 self.assertEqual(self.last_exception.args[0], "hello")596 def testJsWrappedPythonFunctionCannotReturnLong(self):597 def hai2u(cx, this, args):598 return sys.maxint + 1 # Should be a PyLong object.599 self.assertRaises(NotImplementedError,600 self._evalJsWrappedPyFunc,601 hai2u, 'hai2u()')602 def testJsWrappedPythonFunctionRaisesUnicodeDecodeError(self):603 def hai2u(cx, this, args):604 return "o hai\xc3"605 self.assertRaises(UnicodeDecodeError,606 self._evalJsWrappedPyFunc,607 hai2u, 'hai2u()')608 def testJsWrappedPythonFunctionReturnsNone(self):609 def hai2u(cx, this, args):610 pass611 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),612 None)613 def testJsWrappedPythonFunctionReturnsTrue(self):614 def hai2u(cx, this, args):615 return True616 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),617 True)618 def testJsWrappedPythonFunctionReturnsFalse(self):619 def hai2u(cx, this, args):620 return False621 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),622 False)623 def testJsWrappedPythonFunctionReturnsSmallInt(self):624 def hai2u(cx, this, args):625 return 5626 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),627 5)628 def testJsWrappedPythonFunctionReturnsFloat(self):629 def hai2u(cx, this, args):630 return 5.1631 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),632 5.1)633 def testJsWrappedPythonFunctionReturnsNegativeInt(self):634 def hai2u(cx, this, args):635 return -5636 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),637 -5)638 def testJsWrappedPythonFunctionReturnsBigInt(self):639 def hai2u(cx, this, args):640 return 2147483647641 self.assertEqual(self._evalJsWrappedPyFunc(hai2u, 'hai2u()'),642 2147483647)643 def testDefinePropertyWorksWithIntegers(self):644 cx = pydermonkey.Runtime().new_context()645 obj = cx.new_object()646 cx.define_property(obj, 0, 'test')647 self.assertEqual(cx.evaluate_script(obj, "this[0]", '<string>', 1),648 'test')649 def testGetPropertyDoesNotWorkWithFloats(self):650 cx = pydermonkey.Runtime().new_context()651 obj = cx.new_object()652 self.assertRaises(TypeError,653 cx.get_property,654 obj, 0.534)655 self.assertEqual(self.last_exception.args[0],656 'Property must be a string or integer.')657 def testHasPropertyWorksWithIntegers(self):658 cx = pydermonkey.Runtime().new_context()659 obj = cx.new_object()660 self.assertEqual(cx.has_property(obj, 0), False)661 cx.define_property(obj, 0, 'hi')662 self.assertEqual(cx.has_property(obj, 0), True)663 def testGetPropertyWorksWithIntegers(self):664 cx = pydermonkey.Runtime().new_context()665 obj = cx.new_object()666 cx.init_standard_classes(obj)667 array = cx.evaluate_script(obj, "['test']", '<string>', 1)668 self.assertEqual(cx.get_property(array, 0), 'test')669 def testHasPropertyWorks(self):670 cx = pydermonkey.Runtime().new_context()671 obj = cx.new_object()672 cx.init_standard_classes(obj)673 foo = cx.new_object()674 cx.define_property(obj, u"foo\u2026", foo)675 self.assertTrue(cx.has_property(obj, u"foo\u2026"))676 self.assertFalse(cx.has_property(obj, "bar"))677 def testDefinePropertyWorksWithUnicodePropertyNames(self):678 cx = pydermonkey.Runtime().new_context()679 obj = cx.new_object()680 cx.init_standard_classes(obj)681 foo = cx.new_object()682 cx.define_property(obj, u"foo\u2026", foo)683 self.assertEqual(684 cx.get_property(obj, u"foo\u2026"),685 foo686 )687 def testDefinePropertyWorksWithObject(self):688 cx = pydermonkey.Runtime().new_context()689 obj = cx.new_object()690 cx.init_standard_classes(obj)691 foo = cx.new_object()692 cx.define_property(obj, "foo", foo)693 self.assertEqual(694 cx.evaluate_script(obj, 'foo', '<string>', 1),695 foo696 )697 def testDefinePropertyWorksWithString(self):698 cx = pydermonkey.Runtime().new_context()699 obj = cx.new_object()700 cx.init_standard_classes(obj)701 foo = cx.new_object()702 cx.define_property(obj, "foo", u"hello")703 self.assertEqual(704 cx.evaluate_script(obj, 'foo', '<string>', 1),705 u"hello"706 )707 def testObjectIsIdentityPreserving(self):708 cx = pydermonkey.Runtime().new_context()709 obj = cx.new_object()710 cx.init_standard_classes(obj)711 cx.evaluate_script(obj, 'var foo = {bar: 1}', '<string>', 1)712 self.assertTrue(isinstance(cx.get_property(obj, u"foo"),713 pydermonkey.Object))714 self.assertTrue(cx.get_property(obj, u"foo") is715 cx.get_property(obj, "foo"))716 def testObjectGetattrThrowsException(self):717 cx = pydermonkey.Runtime().new_context()718 obj = cx.new_object()719 cx.init_standard_classes(obj)720 result = cx.evaluate_script(obj, '({get foo() { throw "blah"; }})',721 '<string>', 1)722 self.assertRaises(pydermonkey.ScriptError,723 cx.get_property,724 result,725 u"foo")726 self.assertEqual(self.last_exception.args[0], u"blah")727 def testInfiniteRecursionRaisesError(self):728 cx = pydermonkey.Runtime().new_context()729 obj = cx.new_object()730 cx.init_standard_classes(obj)731 self.assertRaises(732 pydermonkey.ScriptError,733 cx.evaluate_script,734 obj, '(function foo() { foo(); })();', '<string>', 1735 )736 self.assertEqual(737 self._tostring(cx, self.last_exception.args[0]),738 "InternalError: too much recursion"739 )740 def testObjectGetattrWorks(self):741 cx = pydermonkey.Runtime().new_context()742 obj = cx.new_object()743 cx.init_standard_classes(obj)744 cx.evaluate_script(obj, 'var boop = 5', '<string>', 1)745 cx.evaluate_script(obj, 'this["blarg\u2026"] = 5', '<string>', 1)746 self.assertEqual(cx.get_property(obj, u"beans"),747 pydermonkey.undefined)748 self.assertEqual(cx.get_property(obj, u"blarg\u2026"), 5)749 self.assertEqual(cx.get_property(obj, u"boop"), 5)750 def testContextIsInstance(self):751 cx = pydermonkey.Runtime().new_context()752 self.assertTrue(isinstance(cx, pydermonkey.Context))753 def testContextTypeCannotBeInstantiated(self):754 self.assertRaises(TypeError, pydermonkey.Context)755 def testObjectIsInstance(self):756 obj = pydermonkey.Runtime().new_context().new_object()757 self.assertTrue(isinstance(obj, pydermonkey.Object))758 self.assertFalse(isinstance(obj, pydermonkey.Function))759 def testObjectTypeCannotBeInstantiated(self):760 self.assertRaises(TypeError, pydermonkey.Object)761 def testFunctionIsInstance(self):762 def boop():763 pass764 obj = pydermonkey.Runtime().new_context().new_function(boop, "boop")765 self.assertTrue(isinstance(obj, pydermonkey.Object))766 self.assertTrue(isinstance(obj, pydermonkey.Function))767 def testFunctionTypeCannotBeInstantiated(self):768 self.assertRaises(TypeError, pydermonkey.Function)769 def testObjectGetRuntimeWorks(self):770 rt = pydermonkey.Runtime()771 obj = rt.new_context().new_object()772 self.assertEqual(obj.get_runtime(), rt)773 def testContextGetRuntimeWorks(self):774 rt = pydermonkey.Runtime()775 cx = rt.new_context()776 self.assertEqual(cx.get_runtime(), rt)777 def testRuntimesAreWeakReferencable(self):778 rt = pydermonkey.Runtime()779 wrt = weakref.ref(rt)780 self.assertEqual(rt, wrt())781 del rt782 self.assertEqual(wrt(), None)783 def testContextsAreWeakReferencable(self):784 rt = pydermonkey.Runtime()785 cx = rt.new_context()786 wcx = weakref.ref(cx)787 self.assertEqual(cx, wcx())788 del cx789 self.assertEqual(wcx(), None)790 def testUndefinedCannotBeInstantiated(self):791 self.assertRaises(TypeError, pydermonkey.undefined)792 def testEvaluateThrowsException(self):793 cx = pydermonkey.Runtime().new_context()794 obj = cx.new_object()795 self.assertRaises(pydermonkey.ScriptError,796 cx.evaluate_script,797 obj, 'hai2u()', '<string>', 1)798 self.assertEqual(self._tostring(cx,799 self.last_exception.args[0]),800 'ReferenceError: hai2u is not defined')801 def testThrowingObjWithBadToStringWorks(self):802 self.assertRaises(803 pydermonkey.ScriptError,804 self._evaljs,805 "throw {toString: function() { throw 'dujg' }}"806 )807 self.assertEqual(808 self.last_exception.args[1],809 "<string conversion failed>"810 )811 def testEvaluateTakesUnicodeCode(self):812 self.assertEqual(self._evaljs(u"'foo\u2026'"),813 u"foo\u2026")814 def testEvaluateReturnsUndefined(self):815 retval = self._evaljs("")816 self.assertTrue(retval is pydermonkey.undefined)817 def testEvaludateReturnsUnicodeWithEmbeddedNULs(self):818 retval = self._evaljs("'\x00hi'")819 self.assertEqual(retval, u'\x00hi')820 def testEvaluateReturnsSMPUnicode(self):821 # This is 'LINEAR B SYLLABLE B008 A', in the supplementary822 # multilingual plane (SMP).823 retval = self._evaljs("'\uD800\uDC00'")824 self.assertEqual(retval, u'\U00010000')825 self.assertEqual(retval.encode('utf-16'),826 '\xff\xfe\x00\xd8\x00\xdc')827 def testEvaluateReturnsBMPUnicode(self):828 retval = self._evaljs("'o hai\u2026'")829 self.assertTrue(type(retval) == unicode)830 self.assertEqual(retval, u'o hai\u2026')831 def testEvaluateReturnsObject(self):832 cx = pydermonkey.Runtime().new_context()833 obj = cx.new_object()834 cx.init_standard_classes(obj)835 obj = cx.evaluate_script(obj, '({boop: 1})', '<string>', 1)836 self.assertTrue(isinstance(obj, pydermonkey.Object))837 self.assertEqual(cx.get_property(obj, u"boop"), 1)838 def testScriptedFunctionsHaveFilenameInfo(self):839 cx = pydermonkey.Runtime().new_context()840 obj = cx.new_object()841 cx.init_standard_classes(obj)842 jsfunc = cx.evaluate_script(obj,843 '(function boop() { \nreturn 1; })',844 'somefile', 5)845 self.assertEqual(jsfunc.filename, 'somefile')846 self.assertEqual(jsfunc.base_lineno, 5)847 self.assertEqual(jsfunc.line_extent, 2)848 def testEvaluateReturnsFunction(self):849 cx = pydermonkey.Runtime().new_context()850 obj = cx.new_object()851 cx.init_standard_classes(obj)852 obj = cx.evaluate_script(obj, '(function boop() { return 1; })',853 '<string>', 1)854 self.assertTrue(isinstance(obj, pydermonkey.Function))855 def testJsExceptionStateIsClearedAfterExceptionIsCaught(self):856 cx = pydermonkey.Runtime().new_context()857 obj = cx.new_object()858 self.assertRaises(pydermonkey.ScriptError,859 cx.evaluate_script,860 obj, 'blah()', '<string>', 1)861 self.assertEqual(cx.evaluate_script(obj, '5+3', '<string>', 1),862 8)863 def testTypeConversionNotImplementedMentionsTypeName(self):864 cx = pydermonkey.Runtime().new_context()865 obj = cx.new_object()866 self.assertRaises(867 NotImplementedError,868 cx.define_property,869 obj, 'hi', sys.maxint + 1870 )871 self.assertEqual(872 self.last_exception.args[0],873 "Data type conversion not implemented for type 'long'."874 )875 def testCallFunctionRaisesErrorOnBadFuncArgs(self):876 cx = pydermonkey.Runtime().new_context()877 obj = cx.new_object()878 obj = cx.evaluate_script(879 obj,880 '(function boop(a, b) { return a+b+this.c; })',881 '<string>', 1882 )883 self.assertRaises(884 NotImplementedError,885 cx.call_function,886 obj, obj, (1, self)887 )888 def _tostring(self, cx, obj):889 return cx.call_function(obj,890 cx.get_property(obj, u"toString"),891 ())892 def testCallFunctionRaisesErrorFromJS(self):893 cx = pydermonkey.Runtime().new_context()894 obj = cx.new_object()895 obj = cx.evaluate_script(896 obj,897 '(function boop(a, b) { blarg(); })',898 '<string>', 1899 )900 self.assertRaises(pydermonkey.ScriptError,901 cx.call_function,902 obj, obj, (1,))903 self.assertEqual(self._tostring(cx,904 self.last_exception.args[0]),905 'ReferenceError: blarg is not defined')906 def testInitStandardClassesRaisesExcOnRuntimeMismatch(self):907 cx2 = pydermonkey.Runtime().new_context()908 cx = pydermonkey.Runtime().new_context()909 obj = cx.new_object()910 self.assertRaises(ValueError,911 cx2.init_standard_classes,912 obj)913 self.assertEqual(self.last_exception.args[0],914 'JS runtime mismatch')915 def testCallFunctionWorks(self):916 cx = pydermonkey.Runtime().new_context()917 obj = cx.new_object()918 thisArg = cx.new_object()919 cx.define_property(thisArg, "c", 3)920 cx.init_standard_classes(obj)921 obj = cx.evaluate_script(922 obj,923 '(function boop(a, b) { return a+b+this.c; })',924 '<string>', 1925 )926 self.assertEqual(cx.call_function(thisArg, obj, (1,2)), 6)927 def testGetVersionWorks(self):928 # Note that this will change someday.929 self.assertEqual(pydermonkey.Runtime().new_context().get_version(),930 "1.8")931 def testSetGCZealWorks(self):932 cx = pydermonkey.Runtime().new_context()933 for i in range(3):934 pydermonkey.set_default_gc_zeal(i)935 cx.set_gc_zeal(i)936 for i in [-1, 3]:937 self.assertRaises(ValueError, cx.set_gc_zeal, i)938 self.assertRaises(ValueError, pydermonkey.set_default_gc_zeal, i)939 def testEvaluateReturnsTrue(self):940 self.assertTrue(self._evaljs('true') is True)941 def testEvaluateReturnsFalse(self):942 self.assertTrue(self._evaljs('false') is False)943 def testEvaluateReturnsNone(self):944 self.assertTrue(self._evaljs('null') is None)945 def testEvaluateReturnsIntegers(self):946 self.assertEqual(self._evaljs('1+3'), 4)...
views.py
Source:views.py
1from django.contrib.auth.mixins import LoginRequiredMixin2from django.contrib import messages3from django.db.models import Count4from django.urls import reverse5from django.views import generic, View6from . import models7from . import forms8from django.shortcuts import render, redirect, get_object_or_4049from .security import IsRedactorMixin, IsRedactorQuestionsAuthorMixin, IsNumberOfReviewsExceededMixin, \10 HasExpertAddedReviewMixin, IsExpertMixin,IsExpertAuthorOfReviewMixin11from django.contrib.auth import views as auth_views12class ExpertListView(LoginRequiredMixin, generic.ListView):13 model = models.Expert14 login_url = '/login'15 redirect_field_name = 'redirect_to'16class ExpertDetailView(LoginRequiredMixin, generic.DetailView):17 model = models.Expert18 login_url = '/login'19 redirect_field_name = 'redirect_to'20 def get_context_data(self, **kwargs):21 context = super(ExpertDetailView, self).get_context_data(**kwargs)22 context['prev_order'] = self.request.GET.get('order', 'created')23 context['title'] = self.request.GET.get('title', '')24 context['prev_category'] = self.request.GET.get('category', '')25 context['orders'] = (26 'Od najnowszego', 'Od najstarszego', 'Najpopularniejsze', 'Najmniej popularne', 'Najbardziej oceniane',27 'Najmniej oceniane')28 context['categories'] = models.Category.objects.all()29 list_of_reviews = models.Review.objects.filter(expert=self.kwargs['pk'])30 list_of_question = [x.question_for_expert.id for x in list_of_reviews]31 new_context = models.QuestionForExpert.objects.filter(id__in=list_of_question)32 if context['prev_category'] != '':33 new_context = new_context.filter(categories__in=[context['prev_category']])34 if context['title'] != '':35 new_context = new_context.filter(title__icontains=context['title'])36 if context['prev_order'] == 'Od najnowszego':37 new_context = new_context.order_by('created')38 elif context['prev_order'] == 'Od najstarszego':39 new_context = new_context.order_by('-created')40 elif context['prev_order'] == 'Najpopularniejsze':41 new_context = new_context.order_by('-views')42 elif context['prev_order'] == 'Najmniej popularne':43 new_context = new_context.order_by('views')44 elif context['prev_order'] == 'Najbardziej oceniane':45 new_context = new_context.annotate(num_reviews=Count('review')).order_by('-num_reviews')46 elif context['prev_order'] == 'Najmniej oceniane':47 new_context = new_context.annotate(num_reviews=Count('review')).order_by('num_reviews')48 context['questions'] = new_context49 return context50class RedactorListView(LoginRequiredMixin, generic.ListView):51 model = models.Redactor52 login_url = '/login'53 redirect_field_name = 'redirect_to'54class RedactorDetailView(LoginRequiredMixin, generic.DetailView):55 model = models.Redactor56 login_url = '/login'57 redirect_field_name = 'redirect_to'58 def get_context_data(self, **kwargs):59 context = super(RedactorDetailView, self).get_context_data(**kwargs)60 context['prev_order'] = self.request.GET.get('order', 'created')61 context['title'] = self.request.GET.get('title', '')62 context['prev_category'] = self.request.GET.get('category', '')63 context['orders'] = (64 'Od najnowszego', 'Od najstarszego', 'Najpopularniejsze', 'Najmniej popularne', 'Najbardziej oceniane',65 'Najmniej oceniane')66 context['categories'] = models.Category.objects.all()67 new_context = models.QuestionForExpert.objects.filter(redactor=self.kwargs['pk'])68 if context['prev_category'] != '':69 new_context = new_context.filter(categories__in=[context['prev_category']])70 if context['title'] != '':71 new_context = new_context.filter(title__icontains=context['title'])72 if context['prev_order'] == 'Od najnowszego':73 new_context = new_context.order_by('created')74 elif context['prev_order'] == 'Od najstarszego':75 new_context = new_context.order_by('-created')76 elif context['prev_order'] == 'Najpopularniejsze':77 new_context = new_context.order_by('-views')78 elif context['prev_order'] == 'Najmniej popularne':79 new_context = new_context.order_by('views')80 elif context['prev_order'] == 'Najbardziej oceniane':81 new_context = new_context.annotate(num_reviews=Count('review')).order_by('-num_reviews')82 elif context['prev_order'] == 'Najmniej oceniane':83 new_context = new_context.annotate(num_reviews=Count('review')).order_by('num_reviews')84 context['questions'] = new_context85 return context86class ReviewCreateView(LoginRequiredMixin,IsExpertMixin, HasExpertAddedReviewMixin, generic.CreateView):87 model = models.Review88 form_class = forms.ReviewForm89 template_name = 'fakechecker/review_create.html'90 def get_success_url(self):91 return reverse('QuestionForExpert_detail', kwargs={'pk': self.kwargs['question_for_expert_id']})92 def get_context_data(self, **kwargs):93 context = super(ReviewCreateView, self).get_context_data(**kwargs)94 context['question_for_expert'] = get_object_or_404(models.QuestionForExpert,95 pk=self.kwargs['question_for_expert_id'])96 return context97 def form_valid(self, form, *args, **kwargs):98 question_for_expert = get_object_or_404(models.QuestionForExpert, id=self.kwargs['question_for_expert_id'])99 self.object = form.save(commit=False)100 self.object.question_for_expert = question_for_expert101 self.object.expert = self.request.user.expert102 self.object.save()103 return super().form_valid(form)104 def form_invalid(self, form):105 return super().form_invalid(form)106class ReviewUpdateView(LoginRequiredMixin,107 IsExpertMixin,108 IsExpertAuthorOfReviewMixin,109 generic.UpdateView):110 model = models.Review111 form_class = forms.ReviewForm112 pk_url_kwarg = "pk"113class CategoryListView(LoginRequiredMixin,114 IsRedactorMixin,115 generic.ListView):116 model = models.Category117 form_class = forms.CategoryForm118class CategoryCreateView(LoginRequiredMixin,119 IsRedactorMixin,120 generic.CreateView):121 model = models.Category122 form_class = forms.CategoryForm123class CategoryDetailView(generic.DetailView):124 model = models.Category125 form_class = forms.CategoryForm126 template_name = 'fakechecker/category_detail.html'127 def get_context_data(self, **kwargs):128 context = super(CategoryDetailView, self).get_context_data(**kwargs)129 context['prev_order'] = self.request.GET.get('order', 'created')130 context['title'] = self.request.GET.get('title', '')131 category = self.kwargs['pk']132 context['orders'] = ('Od najnowszego', 'Od najstarszego')133 new_context = models.Question.objects.select_subclasses()134 if category != '':135 new_context = new_context.filter(categories__in=[category])136 if context['title'] != '':137 new_context = new_context.filter(title__icontains=context['title'])138 if context['prev_order'] == 'Od najnowszego':139 new_context = new_context.order_by('created')140 elif context['prev_order'] == 'Od najstarszego':141 new_context = new_context.order_by('-created')142 context['questions'] = new_context143 return context144class CategoryUpdateView(LoginRequiredMixin,145 IsRedactorMixin,146 generic.UpdateView):147 model = models.Category148 form_class = forms.CategoryForm149 pk_url_kwarg = "pk"150class QuestionFromUserListView(LoginRequiredMixin,151 IsRedactorMixin,152 generic.ListView):153 model = models.QuestionFromUser154 form_class = forms.QuestionFromUserForm155 template_name = 'fakechecker/question_from_user_list.html'156 def get_queryset(self):157 category = self.request.GET.get('category', '')158 is_read = self.request.GET.get('read', '')159 title = self.request.GET.get('title', '')160 order = self.request.GET.get('order', 'created')161 new_context = models.QuestionFromUser.objects.all()162 if category != '':163 new_context = new_context.filter(categories__in=[category])164 if is_read == 'Tylko nowe':165 new_context = new_context.filter(is_read=False)166 elif is_read == 'Tylko przeczytane':167 new_context = new_context.filter(is_read=True)168 if title != '':169 new_context = new_context.filter(title__icontains=title)170 if order == 'Od najnowszego':171 new_context = new_context.order_by('created')172 elif order == 'Od najstarszego':173 new_context = new_context.order_by('-created')174 return new_context175 def get_context_data(self, **kwargs):176 context = super(QuestionFromUserListView, self).get_context_data(**kwargs)177 context['prev_order'] = self.request.GET.get('order', 'created')178 context['prev_read'] = self.request.GET.get('read', '')179 context['prev_category'] = self.request.GET.get('category', '')180 context['title'] = self.request.GET.get('title', '')181 context['orders'] = ('Od najnowszego', 'Od najstarszego')182 context['is_read'] = ('Wszystkie', 'Tylko nowe', 'Tylko przeczytane')183 context['categories'] = models.Category.objects.all()184 context['question_collections'] = models.QuestionCollection.objects.filter(redactor=self.request.user.redactor)185 return context186class QuestionFromUserCreateView(generic.CreateView):187 model = models.QuestionFromUser188 form_class = forms.QuestionFromUserForm189 template_name = 'fakechecker/question_from_user_form.html'190class QuestionFromUserDetailView(generic.DetailView):191 model = models.QuestionFromUser192 form_class = forms.QuestionFromUserForm193 pk_url_kwarg = "pk"194 template_name = 'fakechecker/question_from_user_detail.html'195class QuestionForExpertListView(generic.ListView):196 model = models.QuestionForExpert197 form_class = forms.QuestionForExpertForm198 template_name = 'fakechecker/question_for_expert_list.html'199 def get_queryset(self):200 category = self.request.GET.get('category', '')201 title = self.request.GET.get('title', '')202 order = self.request.GET.get('order', 'created')203 new_context = models.QuestionForExpert.objects.all()204 if category != '':205 new_context = new_context.filter(categories__in=[category])206 if title != '':207 new_context = new_context.filter(title__icontains=title)208 if order == 'Od najnowszego':209 new_context = new_context.order_by('created')210 elif order == 'Od najstarszego':211 new_context = new_context.order_by('-created')212 elif order == 'Najpopularniejsze':213 new_context = new_context.order_by('-views')214 elif order == 'Najmniej popularne':215 new_context = new_context.order_by('views')216 elif order == 'Najbardziej oceniane':217 new_context = new_context.annotate(num_reviews=Count('review')).order_by('-num_reviews')218 elif order == 'Najmniej oceniane':219 new_context = new_context.annotate(num_reviews=Count('review')).order_by('num_reviews')220 return new_context221 def get_context_data(self, **kwargs):222 context = super(QuestionForExpertListView, self).get_context_data(**kwargs)223 context['prev_order'] = self.request.GET.get('order', 'created')224 context['title'] = self.request.GET.get('title', '')225 context['prev_read'] = self.request.GET.get('read', '')226 context['prev_category'] = self.request.GET.get('category', '')227 context['orders'] = (228 'Od najnowszego', 'Od najstarszego', 'Najpopularniejsze', 'Najmniej popularne', 'Najbardziej oceniane',229 'Najmniej oceniane')230 context['is_read'] = ('Wszystkie', 'Tylko nowe', 'Tylko przeczytane')231 context['categories'] = models.Category.objects.all()232 return context233class QuestionForExpertCreateView(LoginRequiredMixin, IsRedactorMixin, View):234 login_url = '/login'235 redirect_field_name = 'redirect_to'236 def get(self, request):237 return render(request, 'fakechecker/question_for_expert_form.html', {238 'question_for_expert_form': forms.QuestionForExpertForm,239 })240 def post(self, request):241 expert_question = models.QuestionForExpert(242 title=request.POST.get('title'),243 content=request.POST.get('content'),244 sources=request.POST.get('sources'),245 redactor=request.user.redactor,246 )247 expert_question.save()248 expert_question.categories.set(request.POST.getlist('categories'))249 return redirect("QuestionForExpert_list")250class QuestionForExpertDetailView(generic.DetailView):251 model = models.QuestionForExpert252 form_class = forms.QuestionForExpertForm253 template_name = 'fakechecker/question_for_expert_detail.html'254 def get_context_data(self, **kwargs):255 context = super(QuestionForExpertDetailView, self).get_context_data(**kwargs)256 try:257 context['expert_posted'] = context['object'].review_set.filter(expert_id=self.request.user.expert).count()258 except:259 context['expert_posted'] = 0260 return context261class QuestionForExpertUpdateView(LoginRequiredMixin,262 IsRedactorMixin,263 IsRedactorQuestionsAuthorMixin,264 IsNumberOfReviewsExceededMixin,265 View):266 login_url = '/login'267 redirect_field_name = 'redirect_to'268 def get(self, request, **kwargs):269 object = get_object_or_404(models.QuestionForExpert, pk=kwargs['pk'])270 return render(request, 'fakechecker/question_for_expert_form.html', {271 'question_for_expert_form': forms.QuestionForExpertForm(initial={272 'title': object.title,273 'content': object.content,274 'sources': object.sources,275 'categories': object.categories.all(),276 }),277 })278 def post(self, request, **kwargs):279 expert_question = get_object_or_404(models.QuestionForExpert, pk=kwargs['pk'])280 expert_question.title = request.POST.get('title')281 expert_question.content = request.POST.get('content')282 expert_question.sources = request.POST.get('sources')283 expert_question.save()284 expert_question.categories.set(request.POST.getlist('categories'))285 return redirect("QuestionForExpert_list")286class LoginView(auth_views.LoginView):287 template_name = "fakechecker/login.html"288 form_class = forms.CustomAuthenticationForm289class LogoutView(auth_views.LogoutView):290 template_name = "fakechecker/logout.html"291 def get_next_page(self):292 next_page = super(LogoutView, self).get_next_page()293 messages.add_message(294 self.request, messages.SUCCESS,295 'ZostaÅeÅ wylogowany pomyÅlnie!'296 )297 return next_page298def ExpertHowToBe(request):...
test_allocation.py
Source:test_allocation.py
1from common import * # NOQA2from test_shared_volumes import add_storage_pool3def test_inactive_agent(super_client, new_context):4 host = super_client.reload(new_context.host)5 agent = host.agent()6 c = new_context.create_container()7 assert c.state == 'running'8 agent = super_client.wait_success(agent.deactivate())9 assert agent.state == 'inactive'10 c = new_context.create_container_no_success()11 assert c.transitioning == 'error'12 assert c.transitioningMessage == \13 'Allocation failed: No healthy hosts with sufficient ' \14 'resources available'15 assert c.state == 'error'16def test_allocation_with_shared_storage_pool(super_client, new_context):17 count = 318 client = new_context.client19 host2 = register_simulated_host(client)20 register_simulated_host(client)21 hosts = [new_context.host, host2]22 hosts = wait_all_success(super_client, hosts)23 sp = add_storage_pool(new_context, [new_context.host.uuid, host2.uuid])24 sp_name = sp.name25 for h in hosts:26 assert h.state == 'active'27 assert h.agent().state == 'active'28 assert len(h.storagePools()) == 229 assert h.storagePools()[0].state == 'active'30 assert h.storagePools()[1].state == 'active'31 # Create a volume with a driver that points to a storage pool32 v1 = client.create_volume(name=random_str(), driver=sp_name)33 v1 = client.wait_success(v1)34 assert v1.state == 'inactive'35 data_volume_mounts = {'/con/path': v1.id}36 containers = []37 for _ in range(len(hosts) * count):38 c = client.create_container(imageUuid=new_context.image_uuid,39 dataVolumeMounts=data_volume_mounts)40 containers.append(c)41 time.sleep(1) # Sleep makes the test faster as it reduces contention42 wait_all_success(super_client, containers, timeout=60)43 for c in containers:44 new_context.wait_for_state(c, 'running')45def test_allocation_stay_associated_to_host(super_client, context):46 c = context.create_container()47 c = context.client.wait_success(c.stop())48 assert c.state == 'stopped'49 assert len(c.hosts()) == 150def test_port_constraint(new_context):51 host1 = new_context.host52 client = new_context.client53 image_uuid = new_context.image_uuid54 containers = []55 try:56 c = client.wait_success(57 client.create_container(imageUuid=image_uuid,58 requestedHostId=host1.id,59 ports=['8081:81/tcp']))60 containers.append(c)61 # try to deploy another container with same public port + protocol62 c2 = client.wait_transitioning(63 client.create_container(imageUuid=image_uuid,64 ports=['8081:81/tcp']))65 assert c2.transitioning == 'error'66 assert 'Allocation failed: host needs ports 8081/tcp available' in \67 c2.transitioningMessage68 assert c2.state == 'error'69 # try different public port70 c3 = new_context.super_create_container(imageUuid=image_uuid,71 ports=['8082:81/tcp'])72 containers.append(c3)73 # try different protocol74 c4 = client.wait_success(75 client.create_container(imageUuid=image_uuid,76 ports=['8081:81/udp']))77 containers.append(c4)78 # UDP is now taken79 c5 = client.wait_transitioning(80 client.create_container(imageUuid=image_uuid,81 ports=['8081:81/udp']))82 assert c5.transitioning == 'error'83 assert 'Allocation failed: host needs ports 8081/udp available' in \84 c5.transitioningMessage85 assert c5.state == 'error'86 # try different bind IP87 c6 = client.wait_success(88 client.create_container(imageUuid=image_uuid,89 requestedHostId=host1.id,90 ports=['127.2.2.2:8081:81/tcp']))91 containers.append(c6)92 # Bind IP is now taken93 c7 = client.wait_transitioning(94 client.create_container(imageUuid=image_uuid,95 ports=['127.2.2.2:8081:81/tcp']))96 assert c7.transitioning == 'error'97 assert 'Allocation failed: host needs ports 8081/tcp available' in \98 c7.transitioningMessage99 assert c7.state == 'error'100 # increase host pool and check whether allocator picks other host101 host2 = register_simulated_host(new_context.client)102 c8 = client.wait_success(103 client.create_container(imageUuid=image_uuid,104 ports=['8081:81/tcp']))105 assert c8.hosts()[0].id == host2.id106 containers.append(c8)107 finally:108 for c in containers:109 if c is not None:110 new_context.delete(c)111def test_request_host_override(new_context):112 host = new_context.host113 c = None114 c2 = None115 try:116 c = new_context.super_create_container(validHostIds=[host.id],117 ports=['8081:81/tcp'])118 # try to deploy another container with same public port + protocol119 # however, explicitly specify requestedHostId120 c2 = new_context.super_create_container(requestedHostId=host.id,121 ports=['8081:81/tcp'])122 finally:123 if c is not None:124 new_context.delete(c)125 if c2 is not None:126 new_context.delete(c2)127def test_host_affinity(super_client, new_context):128 host = new_context.host129 host2 = register_simulated_host(new_context)130 host = super_client.update(host, labels={'size': 'huge',131 'latency': 'long'})132 host2 = super_client.update(host2, labels={'size': 'tiny',133 'latency': 'short'})134 containers = []135 try:136 # test affinity137 c = new_context.create_container(138 environment={'constraint:size==huge': ''})139 assert c.hosts()[0].id == host.id140 containers.append(c)141 c = new_context.create_container(142 labels={'io.rancher.scheduler.affinity:host_label': 'size=huge'})143 assert c.hosts()[0].id == host.id144 containers.append(c)145 # test anti-affinity146 c = new_context.create_container(147 environment={'constraint:size!=huge': ''})148 assert c.hosts()[0].id == host2.id149 containers.append(c)150 c = new_context.create_container(151 labels={'io.rancher.scheduler.affinity:host_label_ne':152 'size=huge'})153 assert c.hosts()[0].id == host2.id154 containers.append(c)155 # test soft affinity.156 # prefer size==huge, but latency==~short if possible157 c = new_context.create_container(158 environment={159 'constraint:size==huge': '',160 'constraint:latency==~short': ''161 })162 assert c.hosts()[0].id == host.id163 containers.append(c)164 c = new_context.create_container(165 labels={166 'io.rancher.scheduler.affinity:host_label': 'size=huge',167 'io.rancher.scheduler.affinity:host_label_soft_ne':168 'latency=short'169 })170 assert c.hosts()[0].id == host.id171 containers.append(c)172 # test soft anti-affinity173 c = new_context.create_container(174 environment={'constraint:latency!=~long': ''})175 assert c.hosts()[0].id == host2.id176 containers.append(c)177 c = new_context.create_container(178 labels={'io.rancher.scheduler.affinity:host_label_soft_ne':179 'latency=long'})180 assert c.hosts()[0].id == host2.id181 containers.append(c)182 finally:183 for c in containers:184 new_context.delete(c)185def test_container_affinity(new_context):186 # Two hosts187 register_simulated_host(new_context)188 containers = []189 try:190 name1 = 'affinity' + random_str()191 c1 = new_context.create_container(192 name=name1)193 containers.append(c1)194 c2 = new_context.create_container(195 environment={'affinity:container==' + name1: ''})196 containers.append(c2)197 # check c2 is on same host as c1198 assert c2.hosts()[0].id == c1.hosts()[0].id199 c3 = new_context.create_container(200 labels={'io.rancher.scheduler.affinity:container': name1})201 containers.append(c3)202 # check c3 is on same host as c1203 assert c3.hosts()[0].id == c1.hosts()[0].id204 c4 = new_context.create_container(205 environment={'affinity:container==' + c1.uuid: ''})206 containers.append(c4)207 # check c4 is on same host as c1208 assert c4.hosts()[0].id == c1.hosts()[0].id209 c5 = new_context.create_container(210 labels={211 'io.rancher.scheduler.affinity:container': c1.uuid})212 containers.append(c5)213 # check c5 is on same host as c1214 assert c5.hosts()[0].id == c1.hosts()[0].id215 c6 = new_context.create_container(216 environment={'affinity:container!=' + name1: ''})217 containers.append(c6)218 # check c6 is not on same host as c1219 assert c6.hosts()[0].id != c1.hosts()[0].id220 c7 = new_context.create_container(221 labels={'io.rancher.scheduler.affinity:container_ne': name1})222 containers.append(c7)223 # check c7 is not on same host as c1224 assert c7.hosts()[0].id != c1.hosts()[0].id225 finally:226 for c in containers:227 new_context.delete(c)228def test_container_label_affinity(new_context):229 # Two hosts230 register_simulated_host(new_context)231 containers = []232 try:233 c1_label = random_str()234 c1 = new_context.create_container(235 labels={'foo': c1_label}236 )237 containers.append(c1)238 c2 = new_context.create_container(239 environment={'affinity:foo==' + c1_label: ''})240 containers.append(c2)241 # check c2 is on same host as c1242 assert c2.hosts()[0].id == c1.hosts()[0].id243 c3 = new_context.create_container(244 labels={245 'io.rancher.scheduler.affinity:container_label':246 'foo=' + c1_label}247 )248 containers.append(c3)249 # check c3 is on same host as c1250 assert c3.hosts()[0].id == c1.hosts()[0].id251 c4_label = random_str()252 c4 = new_context.create_container(253 environment={'affinity:foo!=' + c1_label: ''},254 labels={'foo': c4_label}255 )256 containers.append(c4)257 # check c4 is not on same host as c1258 assert c4.hosts()[0].id != c1.hosts()[0].id259 c5 = new_context.create_container(260 environment={261 'affinity:foo!=' + c1_label: '',262 'affinity:foo!=~' + c4_label: ''263 })264 containers.append(c5)265 # since we just specified a soft anti-affinity to c4,266 # check c5 is on same host as c4267 assert c5.hosts()[0].id == c4.hosts()[0].id268 c6 = new_context.create_container(269 environment={270 'affinity:foo!=' + c1_label: '',271 },272 labels={273 'io.rancher.scheduler.affinity:container_label_soft_ne':274 'foo=' + c4_label275 }276 )277 containers.append(c6)278 assert c6.hosts()[0].id == c4.hosts()[0].id279 finally:280 for c in containers:281 new_context.delete(c)282def test_network_mode_constraint(new_context):283 client = new_context.client284 # Three hosts285 register_simulated_host(new_context)286 register_simulated_host(new_context)287 containers = []288 try:289 c1 = new_context.create_container(startOnCreate=False)290 c2 = new_context.create_container(startOnCreate=False,291 networkMode='container',292 networkContainerId=c1.id)293 c1 = client.wait_success(c1.start())294 c2 = client.wait_success(c2.start())295 assert c1.state == 'running'296 containers.append(c1)297 assert c1.state == 'running'298 containers.append(c2)299 assert c1.hosts()[0].id == c2.hosts()[0].id300 finally:301 for c in containers:...
test_context.py
Source:test_context.py
1# -*- coding:utf-8 -*-2#3# Copyright 2015 Red Hat, Inc.4#5# Licensed under the Apache License, Version 2.0 (the "License"); you may6# not use this file except in compliance with the License. You may obtain7# a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14# License for the specific language governing permissions and limitations15# under the License.16import ast17import mock18import six19import testtools20from bandit.core import context21class ContextTests(testtools.TestCase):22 def test_context_create(self):23 ref_context = mock.Mock()24 new_context = context.Context(context_object=ref_context)25 self.assertEqual(ref_context, new_context._context)26 new_context = context.Context()27 self.assertIsInstance(new_context._context, dict)28 def test_repr(self):29 ref_object = dict(spam='eggs')30 expected_repr = '<Context {}>'.format(ref_object)31 new_context = context.Context(context_object=ref_object)32 self.assertEqual(expected_repr, repr(new_context))33 @mock.patch('bandit.core.context.Context._get_literal_value')34 def test_call_args(self, get_literal_value):35 get_literal_value.return_value = 'eggs'36 ref_call = mock.Mock()37 ref_call.args = [mock.Mock(attr='spam'), 'eggs']38 ref_context = dict(call=ref_call)39 new_context = context.Context(context_object=ref_context)40 expected_args = ['spam', 'eggs']41 self.assertListEqual(expected_args, new_context.call_args)42 def test_call_args_count(self):43 ref_call = mock.Mock()44 ref_call.args = ['spam', 'eggs']45 ref_context = dict(call=ref_call)46 new_context = context.Context(context_object=ref_context)47 self.assertEqual(len(ref_call.args), new_context.call_args_count)48 ref_context = dict(call={})49 new_context = context.Context(context_object=ref_context)50 self.assertIsNone(new_context.call_args_count)51 new_context = context.Context()52 self.assertIsNone(new_context.call_args_count)53 def test_call_function_name(self):54 expected_string = 'spam'55 ref_context = dict(name=expected_string)56 new_context = context.Context(context_object=ref_context)57 self.assertEqual(expected_string, new_context.call_function_name)58 new_context = context.Context()59 self.assertIsNone(new_context.call_function_name)60 def test_call_function_name_qual(self):61 expected_string = 'spam'62 ref_context = dict(qualname=expected_string)63 new_context = context.Context(context_object=ref_context)64 self.assertEqual(expected_string, new_context.call_function_name_qual)65 new_context = context.Context()66 self.assertIsNone(new_context.call_function_name_qual)67 @mock.patch('bandit.core.context.Context._get_literal_value')68 def test_call_keywords(self, get_literal_value):69 get_literal_value.return_value = 'eggs'70 ref_keyword1 = mock.Mock(arg='arg1', value=mock.Mock(attr='spam'))71 ref_keyword2 = mock.Mock(arg='arg2', value='eggs')72 ref_call = mock.Mock()73 ref_call.keywords = [ref_keyword1, ref_keyword2]74 ref_context = dict(call=ref_call)75 new_context = context.Context(context_object=ref_context)76 expected_dict = dict(arg1='spam', arg2='eggs')77 self.assertDictEqual(expected_dict, new_context.call_keywords)78 ref_context = dict(call=None)79 new_context = context.Context(context_object=ref_context)80 self.assertIsNone(new_context.call_keywords)81 new_context = context.Context()82 self.assertIsNone(new_context.call_keywords)83 def test_node(self):84 expected_node = 'spam'85 ref_context = dict(node=expected_node)86 new_context = context.Context(context_object=ref_context)87 self.assertEqual(expected_node, new_context.node)88 new_context = context.Context()89 self.assertIsNone(new_context.node)90 def test_string_val(self):91 expected_string = 'spam'92 ref_context = dict(str=expected_string)93 new_context = context.Context(context_object=ref_context)94 self.assertEqual(expected_string, new_context.string_val)95 new_context = context.Context()96 self.assertIsNone(new_context.string_val)97 def test_statement(self):98 expected_string = 'spam'99 ref_context = dict(statement=expected_string)100 new_context = context.Context(context_object=ref_context)101 self.assertEqual(expected_string, new_context.statement)102 new_context = context.Context()103 self.assertIsNone(new_context.statement)104 @mock.patch('bandit.core.utils.get_qual_attr')105 def test_function_def_defaults_qual(self, get_qual_attr):106 get_qual_attr.return_value = 'spam'107 ref_node = mock.Mock(args=mock.Mock(defaults=['spam']))108 ref_context = dict(node=ref_node, import_aliases=None)109 new_context = context.Context(context_object=ref_context)110 self.assertListEqual(['spam'], new_context.function_def_defaults_qual)111 ref_node = mock.Mock(args=mock.Mock(defaults=[]))112 ref_context = dict(node=ref_node, import_aliases=None)113 new_context = context.Context(context_object=ref_context)114 self.assertListEqual([], new_context.function_def_defaults_qual)115 new_context = context.Context()116 self.assertListEqual([], new_context.function_def_defaults_qual)117 def test__get_literal_value(self):118 new_context = context.Context()119 value = ast.Num(42)120 expected = value.n121 self.assertEqual(expected, new_context._get_literal_value(value))122 value = ast.Str('spam')123 expected = value.s124 self.assertEqual(expected, new_context._get_literal_value(value))125 value = ast.List([ast.Str('spam'), ast.Num(42)], ast.Load())126 expected = [ast.Str('spam').s, ast.Num(42).n]127 self.assertListEqual(expected, new_context._get_literal_value(value))128 value = ast.Tuple([ast.Str('spam'), ast.Num(42)], ast.Load())129 expected = (ast.Str('spam').s, ast.Num(42).n)130 self.assertTupleEqual(expected, new_context._get_literal_value(value))131 value = ast.Set([ast.Str('spam'), ast.Num(42)])132 expected = set([ast.Str('spam').s, ast.Num(42).n])133 self.assertSetEqual(expected, new_context._get_literal_value(value))134 value = ast.Dict(['spam', 'eggs'], [42, 'foo'])135 expected = dict(spam=42, eggs='foo')136 self.assertDictEqual(expected, new_context._get_literal_value(value))137 value = ast.Ellipsis()138 self.assertIsNone(new_context._get_literal_value(value))139 value = ast.Name('spam', ast.Load())140 expected = value.id141 self.assertEqual(expected, new_context._get_literal_value(value))142 if six.PY3:143 value = ast.NameConstant(True)144 expected = str(value.value)145 self.assertEqual(expected, new_context._get_literal_value(value))146 if six.PY3:147 value = ast.Bytes(b'spam')148 expected = value.s149 self.assertEqual(expected, new_context._get_literal_value(value))150 self.assertIsNone(new_context._get_literal_value(None))151 @mock.patch('bandit.core.context.Context.call_keywords',152 new_callable=mock.PropertyMock)153 def test_check_call_arg_value(self, call_keywords):154 new_context = context.Context()155 call_keywords.return_value = dict(spam='eggs')156 self.assertTrue(new_context.check_call_arg_value('spam', 'eggs'))157 self.assertTrue(new_context.check_call_arg_value('spam',158 ['spam', 'eggs']))159 self.assertFalse(new_context.check_call_arg_value('spam', 'spam'))160 self.assertFalse(new_context.check_call_arg_value('spam'))161 self.assertFalse(new_context.check_call_arg_value('eggs'))162 new_context = context.Context()163 self.assertIsNone(new_context.check_call_arg_value(None))164 @mock.patch('bandit.core.context.Context.node',165 new_callable=mock.PropertyMock)166 def test_get_lineno_for_call_arg(self, node):167 expected_lineno = 42168 keyword1 = mock.Mock(arg='spam',169 value=mock.Mock(lineno=expected_lineno))170 node.return_value = mock.Mock(keywords=[keyword1])171 new_context = context.Context()172 actual_lineno = new_context.get_lineno_for_call_arg('spam')173 self.assertEqual(expected_lineno, actual_lineno)174 new_context = context.Context()175 missing_lineno = new_context.get_lineno_for_call_arg('eggs')176 self.assertIsNone(missing_lineno)177 def test_get_call_arg_at_position(self):178 expected_arg = 'spam'179 ref_call = mock.Mock()180 ref_call.args = [ast.Str(expected_arg)]181 ref_context = dict(call=ref_call)182 new_context = context.Context(context_object=ref_context)183 self.assertEqual(expected_arg,184 new_context.get_call_arg_at_position(0))185 self.assertIsNone(new_context.get_call_arg_at_position(1))186 ref_call = mock.Mock()187 ref_call.args = []188 ref_context = dict(call=ref_call)189 new_context = context.Context(context_object=ref_context)190 self.assertIsNone(new_context.get_call_arg_at_position(0))191 new_context = context.Context()192 self.assertIsNone(new_context.get_call_arg_at_position(0))193 def test_is_module_being_imported(self):194 ref_context = dict(module='spam')195 new_context = context.Context(context_object=ref_context)196 self.assertTrue(new_context.is_module_being_imported('spam'))197 self.assertFalse(new_context.is_module_being_imported('eggs'))198 new_context = context.Context()199 self.assertFalse(new_context.is_module_being_imported('spam'))200 def test_is_module_imported_exact(self):201 ref_context = dict(imports=['spam'])202 new_context = context.Context(context_object=ref_context)203 self.assertTrue(new_context.is_module_imported_exact('spam'))204 self.assertFalse(new_context.is_module_imported_exact('eggs'))205 new_context = context.Context()206 self.assertFalse(new_context.is_module_being_imported('spam'))207 def test_is_module_imported_like(self):208 ref_context = dict(imports=[['spam'], ['eggs']])209 new_context = context.Context(context_object=ref_context)210 self.assertTrue(new_context.is_module_imported_like('spam'))211 self.assertFalse(new_context.is_module_imported_like('bacon'))212 new_context = context.Context()...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!