Best JavaScript code snippet using storybook-root
lodash-decorators.d.ts
Source:lodash-decorators.d.ts
1// Type definitions for lodash-decorators 1.0.52// Project: https://github.com/steelsojka/lodash-decorators3// Definitions by: Qubo <https://github.com/tkqubo>4// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped5/// <reference path='../lodash/lodash-3.10.d.ts' />6declare module "lodash-decorators" {7 // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts8 export interface ClassDecorator {9 <TFunction extends Function>(target: TFunction): TFunction|void;10 }11 export interface PropertyDecorator {12 (target: Object, propertyKey: string | symbol): void;13 }14 export interface MethodDecorator {15 <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void;16 }17 export interface ParameterDecorator {18 (target: Object, propertyKey: string | symbol, parameterIndex: number): void;19 }20 export interface TypedMethodDecorator<TFunction extends Function> {21 (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<TFunction>): TypedPropertyDescriptor<TFunction> | void;22 }23 export interface MethodDecoratorWithAccessor extends MethodDecorator, Accessor<MethodDecorator> {24 }25 export interface Accessor<T> {26 set: T;27 get: T;28 proto: T;29 }30 export interface DebounceDecorator {31 (wait: number, options?: _.DebounceSettings): MethodDecorator;32 }33 export interface ThrottleDecorator {34 (wait: number, options?: _.ThrottleSettings): MethodDecorator;35 }36 export interface MemoizeDecorator {37 (resolver?: Function): MethodDecorator;38 }39 export interface AfterDecorator {40 (n: number): MethodDecorator;41 }42 export interface BeforeDecorator {43 (n: number): MethodDecorator;44 }45 export interface AryDecorator {46 (n: number): MethodDecorator;47 }48 export interface CurryDecorator {49 (arity?: number): MethodDecorator;50 }51 export interface CurryRightDecorator {52 (arity?: number): MethodDecorator;53 }54 export interface RestParamDecorator {55 (start?: number): MethodDecorator;56 }57 export interface PartialDecorator {58 (func: Function|string, ...args: any[]): MethodDecorator;59 }60 export interface WrapDecorator {61 (wrapper: ((func: Function, ...args: any[]) => any)|string): MethodDecorator;62 }63 export interface ComposeDecorator {64 (...funcs: (Function|string)[]): MethodDecorator;65 }66 export interface DelayDecorator {67 (wait: number, ...args: any[]): MethodDecorator;68 }69 export interface DeferDecorator {70 (...args: any[]): MethodDecorator;71 }72 export interface BindDecorator {73 (): TypedMethodDecorator<(<R>() => R)>;74 <T1>(param1?: T1):75 TypedMethodDecorator<(<R>(param1: T1) => R)>;76 <T1, T2>(param1?: T1, param2?: T2):77 TypedMethodDecorator<(<R>(param1: T1, param2: T2) => R)>;78 <T1, T2, T3>(param1?: T1, param2?: T2, param3?: T3):79 TypedMethodDecorator<(<R>(param1: T1, param2: T2, param3: T3) => R)>;80 <T1, T2, T3, T4>(param1?: T1, param2?: T2, param3?: T3, param4?: T4):81 TypedMethodDecorator<(<R>(param1: T1, param2: T2, param3: T3, param4: T4) => R)>;82 <T1, T2, T3, T4, T5>(param1?: T1, param2?: T2, param3?: T3, param4?: T4, param5?: T5):83 TypedMethodDecorator<(<R>(param1: T1, param2: T2, param3: T3, param4: T4, param5: T5) => R)>;84 <T1, T2, T3, T4, T5, T6>(param1?: T1, param2?: T2, param3?: T3, param4?: T4, param5?: T5, param6?: T6):85 TypedMethodDecorator<(<R>(param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) => R)>;86 }87 export interface BindAllDecorator {88 (...methodNames: string[]): ClassDecorator;89 }90 export interface ModArgsDecorator {91 (...transforms: Function[]): MethodDecorator;92 }93 export const debounce: DebounceDecorator & Accessor<DebounceDecorator>;94 export const Debounce: DebounceDecorator & Accessor<DebounceDecorator>;95 export const throttle: ThrottleDecorator & Accessor<ThrottleDecorator>;96 export const Throttle: ThrottleDecorator & Accessor<ThrottleDecorator>;97 export const memoize: MemoizeDecorator & Accessor<MemoizeDecorator>;98 export const Memoize: MemoizeDecorator & Accessor<MemoizeDecorator>;99 export const after: AfterDecorator & Accessor<AfterDecorator>;100 export const After: AfterDecorator & Accessor<AfterDecorator>;101 export const before: BeforeDecorator & Accessor<BeforeDecorator>;102 export const Before: BeforeDecorator & Accessor<BeforeDecorator>;103 export const ary: AryDecorator & Accessor<AryDecorator>;104 export const Ary: AryDecorator & Accessor<AryDecorator>;105 export const curry: CurryDecorator & Accessor<CurryDecorator>;106 export const Curry: CurryDecorator & Accessor<CurryDecorator>;107 export const curryRight: CurryRightDecorator & Accessor<CurryRightDecorator>;108 export const CurryRight: CurryRightDecorator & Accessor<CurryRightDecorator>;109 export const restParam: RestParamDecorator & Accessor<RestParamDecorator>;110 export const RestParam: RestParamDecorator & Accessor<RestParamDecorator>;111 export const partial: PartialDecorator & Accessor<PartialDecorator>;112 export const Partial: PartialDecorator & Accessor<PartialDecorator>;113 export const partialRight: PartialDecorator & Accessor<PartialDecorator>;114 export const PartialRight: PartialDecorator & Accessor<PartialDecorator>;115 export const wrap: WrapDecorator & Accessor<WrapDecorator>;116 export const Wrap: WrapDecorator & Accessor<WrapDecorator>;117 export const compose: ComposeDecorator & Accessor<ComposeDecorator>;118 export const Compose: ComposeDecorator & Accessor<ComposeDecorator>;119 export const flow: ComposeDecorator & Accessor<ComposeDecorator>;120 export const Flow: ComposeDecorator & Accessor<ComposeDecorator>;121 export const flowRight: ComposeDecorator & Accessor<ComposeDecorator>;122 export const FlowRight: ComposeDecorator & Accessor<ComposeDecorator>;123 export const backflow: ComposeDecorator & Accessor<ComposeDecorator>;124 export const Backflow: ComposeDecorator & Accessor<ComposeDecorator>;125 export const delay: DelayDecorator & Accessor<DelayDecorator>;126 export const Delay: DelayDecorator & Accessor<DelayDecorator>;127 export const defer: DeferDecorator & Accessor<DeferDecorator>;128 export const Defer: DeferDecorator & Accessor<DeferDecorator>;129 export const bind: BindDecorator & Accessor<BindDecorator>;130 export const Bind: BindDecorator & Accessor<BindDecorator>;131 export const bindAll: BindAllDecorator;132 export const BindAll: BindAllDecorator;133 export const modArgs: ModArgsDecorator & Accessor<ModArgsDecorator>;134 export const ModArgs: ModArgsDecorator & Accessor<ModArgsDecorator>;135 export const once: MethodDecoratorWithAccessor;136 export const Once: MethodDecoratorWithAccessor;137 export const spread: MethodDecoratorWithAccessor;138 export const Spread: MethodDecoratorWithAccessor;139 export const rearg: MethodDecoratorWithAccessor;140 export const Rearg: MethodDecoratorWithAccessor;141 export const negate: MethodDecoratorWithAccessor;142 export const Negate: MethodDecoratorWithAccessor;143 export const tap: MethodDecoratorWithAccessor;144 export const Tap: MethodDecoratorWithAccessor;145}146declare module "lodash-decorators/extensions" {147 // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts148 export interface ClassDecorator {149 <TFunction extends Function>(target: TFunction): TFunction|void;150 }151 export interface PropertyDecorator {152 (target: Object, propertyKey: string | symbol): void;153 }154 export interface MethodDecorator {155 <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void;156 }157 export interface ParameterDecorator {158 (target: Object, propertyKey: string | symbol, parameterIndex: number): void;159 }160 export interface DeprecatedDecorator extends MethodDecorator, ClassDecorator {161 methodAction(fn: Function & { name: string }): void;162 }163 export const deprecated: DeprecatedDecorator;164 export const Deprecated: DeprecatedDecorator;165 export const writable: (writable?: boolean) => MethodDecorator;166 export const Writable: (writable?: boolean) => MethodDecorator;167 export const configurable: (configurable?: boolean) => MethodDecorator;168 export const Configurable: (configurable?: boolean) => MethodDecorator;169 export const returnsArg: (index?: number) => MethodDecorator;170 export const ReturnsArg: (index?: number) => MethodDecorator;171 export const enumerable: (enumerable?: boolean) => MethodDecorator;172 export const Enumerable: (enumerable?: boolean) => MethodDecorator;173 export const nonenumerable: MethodDecorator;174 export const Nonenumerable: MethodDecorator;175 export const nonconfigurable: MethodDecorator;176 export const Nonconfigurable: MethodDecorator;177 export const readonly: MethodDecorator;178 export const Readonly: MethodDecorator;179}180declare module "lodash-decorators/validate" {181 // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts182 export interface ClassDecorator {183 <TFunction extends Function>(target: TFunction): TFunction|void;184 }185 export interface PropertyDecorator {186 (target: Object, propertyKey: string | symbol): void;187 }188 export interface MethodDecorator {189 <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void;190 }191 export interface ParameterDecorator {192 (target: Object, propertyKey: string | symbol, parameterIndex: number): void;193 }194 export interface TypedMethodDecorator<TFunction extends Function> {195 (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<TFunction>): TypedPropertyDescriptor<TFunction> | void;196 }197 export interface Predicate<T> {198 (t: T): boolean;199 }200 type Predicates<T> = Predicate<T>|Predicate<T>[];201 export interface ValidateDecorator {202 <T1>(p1: Predicates<T1>):203 TypedMethodDecorator<(<R>(param1: T1) => R)>;204 <T1, T2>(p1: Predicates<T1>, p2?: Predicates<T2>):205 TypedMethodDecorator<(<R>(param1: T1, param2: T2) => R)>;206 <T1, T2, T3>(p1: Predicates<T1>, p2?: Predicates<T2>, p3?: Predicates<T3>):207 TypedMethodDecorator<(<R>(param1: T1, param2: T2, param3: T3) => R)>;208 <T1, T2, T3, T4>(p1: Predicates<T1>, p2?: Predicates<T2>, p3?: Predicates<T3>, p4?: Predicates<T4>):209 TypedMethodDecorator<(<R>(param1: T1, param2: T2, param3: T3, param4: T4) => R)>;210 <T1, T2, T3, T4, T5>(p1: Predicates<T1>, p2?: Predicates<T2>, p3?: Predicates<T3>, p4?: Predicates<T4>, p5?: Predicates<T5>):211 TypedMethodDecorator<(<R>(param1: T1, param2: T2, param3: T3, param4: T4, param5: T5) => R)>;212 <T1, T2, T3, T4, T5, T6>(p1: Predicates<T1>, p2?: Predicates<T2>, p3?: Predicates<T3>, p4?: Predicates<T4>, p5?: Predicates<T5>, p6?: Predicates<T6>):213 TypedMethodDecorator<(<R>(param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) => R)>;214 }215 export interface ValidateReturnDecorator {216 <R>(p1: Predicates<R>): TypedMethodDecorator<((...args: any[]) => R)>;217 }218 export const validate: ValidateDecorator;219 export const Validate: ValidateDecorator;220 export const validateReturn: ValidateReturnDecorator;221 export const ValidateReturn: ValidateReturnDecorator;...
tf_decorator_test.py
Source:tf_decorator_test.py
...21from tensorflow.python.platform import test22from tensorflow.python.platform import tf_logging as logging23from tensorflow.python.util import tf_decorator24from tensorflow.python.util import tf_inspect25def test_tfdecorator(decorator_name, decorator_doc=None):26 def make_tf_decorator(target):27 return tf_decorator.TFDecorator(decorator_name, target, decorator_doc)28 return make_tf_decorator29def test_decorator_increment_first_int_arg(target):30 """This test decorator skips past `self` as args[0] in the bound case."""31 def wrapper(*args, **kwargs):32 new_args = []33 found = False34 for arg in args:35 if not found and isinstance(arg, int):36 new_args.append(arg + 1)37 found = True38 else:39 new_args.append(arg)40 return target(*new_args, **kwargs)41 return tf_decorator.make_decorator(target, wrapper)42def test_function(x):43 """Test Function Docstring."""44 return x + 145@test_tfdecorator('decorator 1')46@test_decorator_increment_first_int_arg47@test_tfdecorator('decorator 3', 'decorator 3 documentation')48def test_decorated_function(x):49 """Test Decorated Function Docstring."""50 return x * 251@test_tfdecorator('decorator')52class TestDecoratedClass(object):53 """Test Decorated Class."""54 def __init__(self, two_attr=2):55 self.two_attr = two_attr56 @property57 def two_prop(self):58 return 259 def two_func(self):60 return 261 @test_decorator_increment_first_int_arg62 def return_params(self, a, b, c):63 """Return parameters."""64 return [a, b, c]65class TfDecoratorTest(test.TestCase):66 def testInitCapturesTarget(self):67 self.assertIs(test_function,68 tf_decorator.TFDecorator('', test_function).decorated_target)69 def testInitCapturesDecoratorName(self):70 self.assertEqual('decorator name',71 tf_decorator.TFDecorator('decorator name',72 test_function).decorator_name)73 def testInitCapturesDecoratorDoc(self):74 self.assertEqual('decorator doc',75 tf_decorator.TFDecorator('', test_function,76 'decorator doc').decorator_doc)77 def testInitCapturesNonNoneArgspec(self):78 argspec = tf_inspect.ArgSpec(79 args=['a', 'b', 'c'],80 varargs=None,81 keywords=None,82 defaults=(1, 'hello'))83 self.assertIs(argspec,84 tf_decorator.TFDecorator('', test_function, '',85 argspec).decorator_argspec)86 def testInitSetsDecoratorNameToTargetName(self):87 self.assertEqual('test_function',88 tf_decorator.TFDecorator('', test_function).__name__)89 def testInitSetsDecoratorDocToTargetDoc(self):90 self.assertEqual('Test Function Docstring.',91 tf_decorator.TFDecorator('', test_function).__doc__)92 def testCallingATFDecoratorCallsTheTarget(self):93 self.assertEqual(124, tf_decorator.TFDecorator('', test_function)(123))94 def testCallingADecoratedFunctionCallsTheTarget(self):95 self.assertEqual((2 + 1) * 2, test_decorated_function(2))96 def testInitializingDecoratedClassWithInitParamsDoesntRaise(self):97 try:98 TestDecoratedClass(2)99 except TypeError:100 self.assertFail()101 def testReadingClassAttributeOnDecoratedClass(self):102 self.assertEqual(2, TestDecoratedClass().two_attr)103 def testCallingClassMethodOnDecoratedClass(self):104 self.assertEqual(2, TestDecoratedClass().two_func())105 def testReadingClassPropertyOnDecoratedClass(self):106 self.assertEqual(2, TestDecoratedClass().two_prop)107 def testNameOnBoundProperty(self):108 self.assertEqual('return_params',109 TestDecoratedClass().return_params.__name__)110 def testDocstringOnBoundProperty(self):111 self.assertEqual('Return parameters.',112 TestDecoratedClass().return_params.__doc__)113def test_wrapper(*args, **kwargs):114 return test_function(*args, **kwargs)115class TfMakeDecoratorTest(test.TestCase):116 def testAttachesATFDecoratorAttr(self):117 decorated = tf_decorator.make_decorator(test_function, test_wrapper)118 decorator = getattr(decorated, '_tf_decorator')119 self.assertIsInstance(decorator, tf_decorator.TFDecorator)120 def testAttachesWrappedAttr(self):121 decorated = tf_decorator.make_decorator(test_function, test_wrapper)122 wrapped_attr = getattr(decorated, '__wrapped__')123 self.assertIs(test_function, wrapped_attr)124 def testSetsTFDecoratorNameToDecoratorNameArg(self):125 decorated = tf_decorator.make_decorator(test_function, test_wrapper,126 'test decorator name')127 decorator = getattr(decorated, '_tf_decorator')128 self.assertEqual('test decorator name', decorator.decorator_name)129 def testSetsTFDecoratorDocToDecoratorDocArg(self):130 decorated = tf_decorator.make_decorator(131 test_function, test_wrapper, decorator_doc='test decorator doc')132 decorator = getattr(decorated, '_tf_decorator')133 self.assertEqual('test decorator doc', decorator.decorator_doc)134 def testSetsTFDecoratorArgSpec(self):135 argspec = tf_inspect.ArgSpec(136 args=['a', 'b', 'c'],137 varargs=None,138 keywords=None,139 defaults=(1, 'hello'))140 decorated = tf_decorator.make_decorator(test_function, test_wrapper, '', '',141 argspec)142 decorator = getattr(decorated, '_tf_decorator')143 self.assertEqual(argspec, decorator.decorator_argspec)144 def testSetsDecoratorNameToFunctionThatCallsMakeDecoratorIfAbsent(self):145 def test_decorator_name(wrapper):146 return tf_decorator.make_decorator(test_function, wrapper)147 decorated = test_decorator_name(test_wrapper)148 decorator = getattr(decorated, '_tf_decorator')149 self.assertEqual('test_decorator_name', decorator.decorator_name)150 def testCompatibleWithNamelessCallables(self):151 class Callable(object):152 def __call__(self):153 pass154 callable_object = Callable()155 # Smoke test: This should not raise an exception, even though156 # `callable_object` does not have a `__name__` attribute.157 _ = tf_decorator.make_decorator(callable_object, test_wrapper)158 partial = functools.partial(test_function, x=1)159 # Smoke test: This should not raise an exception, even though `partial` does160 # not have `__name__`, `__module__`, and `__doc__` attributes.161 _ = tf_decorator.make_decorator(partial, test_wrapper)162class TfDecoratorUnwrapTest(test.TestCase):163 def testUnwrapReturnsEmptyArrayForUndecoratedFunction(self):164 decorators, _ = tf_decorator.unwrap(test_function)165 self.assertEqual(0, len(decorators))166 def testUnwrapReturnsUndecoratedFunctionAsTarget(self):167 _, target = tf_decorator.unwrap(test_function)168 self.assertIs(test_function, target)169 def testUnwrapReturnsFinalFunctionAsTarget(self):170 self.assertEqual((4 + 1) * 2, test_decorated_function(4))171 _, target = tf_decorator.unwrap(test_decorated_function)172 self.assertTrue(tf_inspect.isfunction(target))173 self.assertEqual(4 * 2, target(4))174 def testUnwrapReturnsListOfUniqueTFDecorators(self):175 decorators, _ = tf_decorator.unwrap(test_decorated_function)...
decorator.ts
Source:decorator.ts
...52 meta_ctor.apply(this, args)53 return this54 }55 const decorator_instance = new (<any> DecoratorFactory)(...args)56 function decorator(target: any, prop?: string | symbol, desc?: number | PropertyDescriptor): any {57 const is_constructor = target && target.prototype?.constructor === target58 const is_parameter = typeof desc === 'number'59 if (is_constructor) {60 decorator_instance.cls = target61 // istanbul ignore else62 if (!prop) {63 if (is_parameter) {64 // DecoratorType.ClassParameter65 const index = decorator_instance.index = desc66 const parameters = target[Parameter_Decorator] = target[Parameter_Decorator] ?? []67 while (parameters.length <= index) {68 parameters.push(null)69 }70 parameters[index] = parameters[index] ?? []...
decorator.spec.ts
Source:decorator.spec.ts
...19 make_decorator20} from './decorator'21chai.use(cap)22describe('decorator.ts', function() {23 const GrandpaDecorator = make_abstract_decorator('GrandpaDecorator')24 const ParentDecorator = make_abstract_decorator('ParentDecorator', GrandpaDecorator)25 const TestDecorator = make_decorator('TestDecorator', (a: string, b: number) => ({ a, b }), ParentDecorator)26 class P {27 constructor(_m: string) {28 }29 }30 @TestDecorator('a', 123)31 @TestDecorator('a', 123)32 class A {33 constructor(34 @TestDecorator('a', 123)35 @TestDecorator('a', 123)36 a: number,37 @TestDecorator('a', 123)38 b: string,39 _c: P) {40 }41 @TestDecorator('a', 123)42 @TestDecorator('a', 123)43 async m(44 a: string,45 b: string,46 @TestDecorator('a', 123)47 c: number,48 @TestDecorator('a', 123)49 @TestDecorator('a', 123)50 d: boolean,51 ) {52 }53 @TestDecorator('a', 123)54 d?: P = undefined55 }56 describe('#make_decorator()', function() {57 it('should create decorator', function() {58 const D = make_decorator('D', (a: string, b: number) => ({ a, b }))59 expect(() => new D('asd', 1)).not.to.throw()60 const ins: InstanceType<typeof D> = new D('asd', 1)61 expect(ins).to.be.instanceof(D)62 })63 it('should create decorator with name', function() {64 const D = make_decorator('D', (a: string, b: number) => ({ a, b }))65 expect(D.name).to.equal('D')66 })67 it('should create inherited decorator', function() {68 expect(new TestDecorator('asd', 1)).to.be.instanceof(ParentDecorator)69 })70 })71 describe('#make_abstract_decorator()', function() {72 it('should not be called', function() {73 expect(() => (ParentDecorator as any)()).to.throw('Abstract decorator can\'t be called directly')74 })75 })76 describe('#get_class_decorator()', function() {77 it('should get decorators of class', function() {78 const decorators = get_class_decorator(A)79 expect(decorators).to.have.length(2)80 expect(decorators[0]).to.be.instanceof(TestDecorator)81 })82 it('should return empty array if no decorator exist', function() {83 const decorators = get_class_decorator(P)84 expect(decorators).to.eql([])85 })86 it('should throw errors if not given class', function() {87 expect(() => get_class_decorator({})).to.throw('[object Object] is not constructor.')88 })89 })90 describe('#get_class_parameter_decorator()', function() {91 it('should get constructor parameter decorators of class', function() {92 const decorators = get_class_parameter_decorator(A)93 expect(decorators).to.have.length(2)94 expect(decorators[0]).to.have.length(2)95 expect(decorators[1]).to.have.length(1)96 expect(decorators[0][0]).to.be.instanceof(TestDecorator)97 })98 it('should return empty array if no parameter decorator exist', function() {99 const decorators = get_class_parameter_decorator(P)100 expect(decorators).to.eql([])101 })102 it('should throw errors if not given class', function() {103 expect(() => get_class_parameter_decorator({})).to.throw('[object Object] is not constructor.')104 })105 })106 describe('#get_all_prop_decorator()', function() {107 it('should get all decorators of class property', function() {108 const decorators = get_all_prop_decorator(A)109 expect(decorators?.size).to.equal(2)110 expect(decorators?.get('m')).to.have.length(2)111 expect(decorators?.get('m')?.[0]).to.be.instanceof(TestDecorator)112 })113 it('should throw errors if not given class', function() {114 expect(() => get_all_prop_decorator({})).to.throw('[object Object] is not constructor.')115 })116 })117 describe('#get_prop_decorator()', function() {118 it('should get decorators of specified property', function() {119 const decorators = get_prop_decorator(A, 'm')120 expect(decorators).to.have.length(2)121 expect(decorators[0]).to.be.instanceof(TestDecorator)122 })123 it('should return empty array if no property decorator exist', function() {124 const decorators = get_prop_decorator(P, 'm')125 expect(decorators).to.eql([])126 })127 it('should throw errors if not given class', function() {128 expect(() => get_prop_decorator({}, 'm')).to.throw('[object Object] is not constructor.')129 })130 })131 describe('#get_method_parameter_decorator()', function() {132 it('should get parameters decorators of specified property', function() {133 const decorators = get_method_parameter_decorator(A, 'm')134 expect(decorators).to.have.length(4)135 expect(decorators[0]).to.be.null136 expect(decorators[1]).to.be.null137 expect(decorators[3]).to.have.length(2)138 expect(decorators[3][0]).to.be.instanceof(TestDecorator)139 })140 it('should return empty array if no parameter decorator exist', function() {141 const decorators = get_method_parameter_decorator(P, 'm')142 expect(decorators).to.eql([])143 })144 it('should throw errors if not given class', function() {145 expect(() => get_method_parameter_decorator({}, 'm')).to.throw('[object Object] is not constructor.')146 })147 })148 describe('#get_param_types()', function() {149 it('should get types of constructor parameters', function() {150 expect(get_param_types(A)).to.eql([Number, String, P])151 })152 it('should get types of method parameters', function() {153 expect(get_param_types(A, 'm')).to.eql([String, String, Number, Boolean])154 })155 })156 describe('#get_prop_types()', function() {157 it('should get types of property', function() {158 expect(get_prop_types(A, 'm')).to.equal(Function)159 expect(get_prop_types(A, 'd')).to.eql(P)...
tf_decorator.py
Source:tf_decorator.py
...201. Call `tf_decorator.make_decorator` on your wrapper function. If your21decorator is stateless, or can capture all of the variables it needs to work22with through lexical closure, this is the simplest option. Create your wrapper23function as usual, but instead of returning it, return24`tf_decorator.make_decorator(target, your_wrapper)`. This will attach some25decorator introspection metadata onto your wrapper and return it.26Example:27 def print_hello_before_calling(target):28 def wrapper(*args, **kwargs):29 print('hello')30 return target(*args, **kwargs)31 return tf_decorator.make_decorator(target, wrapper)322. Derive from TFDecorator. If your decorator needs to be stateful, you can33implement it in terms of a TFDecorator. Store whatever state you need in your34derived class, and implement the `__call__` method to do your work before35calling into your target. You can retrieve the target via36`super(MyDecoratorClass, self).decorated_target`, and call it with whatever37parameters it needs.38Example:39 class CallCounter(tf_decorator.TFDecorator):40 def __init__(self, target):41 super(CallCounter, self).__init__('count_calls', target)42 self.call_count = 043 def __call__(self, *args, **kwargs):44 self.call_count += 145 return super(CallCounter, self).decorated_target(*args, **kwargs)46 def count_calls(target):47 return CallCounter(target)48"""49from __future__ import absolute_import50from __future__ import division51from __future__ import print_function52import functools as _functools53import traceback as _traceback54def make_decorator(target,55 decorator_func,56 decorator_name=None,57 decorator_doc='',58 decorator_argspec=None):59 """Make a decorator from a wrapper and a target.60 Args:61 target: The final callable to be wrapped.62 decorator_func: The wrapper function.63 decorator_name: The name of the decorator. If `None`, the name of the64 function calling make_decorator.65 decorator_doc: Documentation specific to this application of66 `decorator_func` to `target`.67 decorator_argspec: The new callable signature of this decorator.68 Returns:...
decorators.py
Source:decorators.py
1import functools2import threading3from test_junkie.builder import Builder4from test_junkie.constants import DecoratorType5class Suite(object):6 def __init__(self, **decorator_kwargs):7 self.decorator_kwargs = decorator_kwargs8 def __call__(self, cls):9 Builder.build_suite_definitions(decorated_function=cls,10 decorator_kwargs=self.decorator_kwargs,11 decorator_type=DecoratorType.TEST_SUITE)12 return cls13class test(object):14 def __init__(self, **decorator_kwargs):15 self.decorator_kwargs = decorator_kwargs16 def __call__(self, decorated_function):17 Builder.build_suite_definitions(decorated_function=decorated_function,18 decorator_kwargs=self.decorator_kwargs,19 decorator_type=DecoratorType.TEST_CASE)20 return decorated_function21class beforeTest(object):22 def __init__(self, **decorator_kwargs):23 self.decorator_kwargs = decorator_kwargs24 def __call__(self, decorated_function):25 Builder.build_suite_definitions(decorated_function=decorated_function,26 decorator_kwargs=self.decorator_kwargs,27 decorator_type=DecoratorType.BEFORE_TEST)28 return decorated_function29class beforeClass(object):30 def __init__(self, **decorator_kwargs):31 self.decorator_kwargs = decorator_kwargs32 def __call__(self, decorated_function):33 Builder.build_suite_definitions(decorated_function=decorated_function,34 decorator_kwargs=self.decorator_kwargs,35 decorator_type=DecoratorType.BEFORE_CLASS)36 return decorated_function37class afterTest(object):38 def __init__(self, **decorator_kwargs):39 self.decorator_kwargs = decorator_kwargs40 def __call__(self, decorated_function):41 Builder.build_suite_definitions(decorated_function=decorated_function,42 decorator_kwargs=self.decorator_kwargs,43 decorator_type=DecoratorType.AFTER_TEST)44 return decorated_function45class afterClass(object):46 def __init__(self, **decorator_kwargs):47 self.decorator_kwargs = decorator_kwargs48 def __call__(self, decorated_function):49 Builder.build_suite_definitions(decorated_function=decorated_function,50 decorator_kwargs=self.decorator_kwargs,51 decorator_type=DecoratorType.AFTER_CLASS)52 return decorated_function53class GroupRules(object):54 def __init__(self, **decorator_kwargs):55 self.decorator_kwargs = decorator_kwargs56 def __call__(self, decorated_function):57 Builder.register_group_rules(decorated_function=decorated_function,58 decorator_kwargs=self.decorator_kwargs,59 decorator_type=DecoratorType.GROUP_RULES)60 return decorated_function61class afterGroup(object):62 def __init__(self, group, **decorator_kwargs):63 self.decorator_kwargs = decorator_kwargs64 self.group = group65 def __call__(self, decorated_function):66 Builder.add_group_rule(suites=self.group,67 decorated_function=decorated_function,68 decorator_kwargs=self.decorator_kwargs,69 decorator_type=DecoratorType.AFTER_GROUP)70 return decorated_function71class beforeGroup(object):72 def __init__(self, group, **decorator_kwargs):73 self.decorator_kwargs = decorator_kwargs74 self.group = group75 def __call__(self, decorated_function):76 Builder.add_group_rule(suites=self.group,77 decorated_function=decorated_function,78 decorator_kwargs=self.decorator_kwargs,79 decorator_type=DecoratorType.BEFORE_GROUP)80 return decorated_function81def synchronized(lock=threading.Lock()):82 def wrapper(f):83 @functools.wraps(f)84 def inner_wrapper(*args, **kw):85 with lock:86 return f(*args, **kw)87 return inner_wrapper...
DecoratorSidebar.jsx
Source:DecoratorSidebar.jsx
1import PropTypes from 'prop-types';2import React from 'react';3import CombinedProvider from 'injection/CombinedProvider';4import connect from 'stores/connect';5import { Spinner } from 'components/common';6import AddDecoratorButton from './AddDecoratorButton';7import DecoratorSummary from './DecoratorSummary';8import DecoratorList from './DecoratorList';9// eslint-disable-next-line import/no-webpack-loader-syntax10import DecoratorStyles from '!style!css!./decoratorStyles.css';11const { DecoratorsActions, DecoratorsStore } = CombinedProvider.get('Decorators');12class DecoratorSidebar extends React.Component {13 static propTypes = {14 decorators: PropTypes.array.isRequired,15 decoratorTypes: PropTypes.object.isRequired,16 onChange: PropTypes.func.isRequired,17 };18 componentDidMount() {19 DecoratorsActions.available();20 }21 _formatDecorator = (decorator) => {22 const { decorators, decoratorTypes, onChange } = this.props;23 const typeDefinition = decoratorTypes[decorator.type] || { requested_configuration: {}, name: `Unknown type: ${decorator.type}` };24 const deleteDecorator = (decoratorId) => onChange(decorators.filter((_decorator) => _decorator.id !== decoratorId));25 const updateDecorator = (id, updatedDecorator) => onChange(decorators.map((_decorator) => (_decorator.id === id ? updatedDecorator : _decorator)));26 return ({27 id: decorator.id,28 title: <DecoratorSummary key={`decorator-${decorator.id}`}29 decorator={decorator}30 decoratorTypes={decoratorTypes}31 onDelete={deleteDecorator}32 onUpdate={updateDecorator}33 typeDefinition={typeDefinition} />,34 });35 };36 _updateOrder = (orderedDecorators) => {37 const { decorators, onChange } = this.props;38 orderedDecorators.forEach((item, idx) => {39 const decorator = decorators.find((i) => i.id === item.id);40 decorator.order = idx;41 });42 onChange(decorators);43 };44 render() {45 const { decoratorTypes, onChange, decorators } = this.props;46 if (!decoratorTypes) {47 return <Spinner />;48 }49 const sortedDecorators = decorators50 .sort((d1, d2) => d1.order - d2.order);51 const nextDecoratorOrder = sortedDecorators.length > 0 ? sortedDecorators[sortedDecorators.length - 1].order + 1 : 0;52 const decoratorItems = sortedDecorators.map(this._formatDecorator);53 const addDecorator = (decorator) => onChange([...decorators, decorator]);54 return (55 <div>56 <AddDecoratorButton decoratorTypes={decoratorTypes} nextOrder={nextDecoratorOrder} onCreate={addDecorator} />57 <div ref={(decoratorsContainer) => { this.decoratorsContainer = decoratorsContainer; }} className={DecoratorStyles.decoratorListContainer}>58 <DecoratorList decorators={decoratorItems} onReorder={this._updateOrder} onChange={onChange} />59 </div>60 </div>61 );62 }63}...
test_repr.py
Source:test_repr.py
...11 assert cure is not cure.decorator12 assert cure is not decorator13 assert cure.decorator is decorator14 assert str(cure()) != f"<cure.decorator at {id_}>"15 assert str(cure.decorator()) != f"<cure.decorator at {id_}>"16 assert str(decorator()) != f"<cure.decorator at {id_}>"17 assert repr(cure()) != f"<cure.decorator at {id_}>"18 assert repr(cure.decorator()) != f"<cure.decorator at {id_}>"19 assert repr(decorator()) != f"<cure.decorator at {id_}>"20 assert str(cure()).startswith("<cure.decorator at")21 assert str(cure.decorator()).startswith("<cure.decorator at")22 assert str(decorator()).startswith("<cure.decorator at")23 assert repr(cure()).startswith("<cure.decorator at")24 assert repr(cure.decorator()).startswith("<cure.decorator at")25 assert repr(decorator()).startswith("<cure.decorator at")26 assert str(cure()) != str(cure)27 assert str(cure()) != str(cure())28 assert str(cure()) != str(cure.decorator())29 assert str(cure()) != str(decorator())30def test_wrapped_repr():31 id_ = hex(id(cure))32 assert str(cure) == f"<cure.decorator at {id_}>"33 assert str(cure.decorator) != f"<cure.decorator at {id_}>"34 assert str(decorator) == str(cure.decorator)35 def wrapped_func():36 pass37 func_id = hex(id(wrapped_func))38 func = cure(wrapped_func)39 start_str = "function test_wrapped_repr.<locals>.wrapped_func at"40 assert str(func) != f"<{start_str} {id_}>"41 assert str(func) != f"<{start_str} {func_id}>"42 assert repr(func) != f"<{start_str} {id_}>"43 assert repr(func) != f"<{start_str} {func_id}>"44 func = cure()(wrapped_func)45 assert str(func) != f"<{start_str} {id_}>"46 assert str(func) != f"<{start_str} {func_id}>"47 assert repr(func) != f"<{start_str} {id_}>"48 assert repr(func) != f"<{start_str} {func_id}>"49 func = cure.decorator(wrapped_func)50 assert str(func) != f"<{start_str} {id_}>"51 assert str(func) != f"<{start_str} {func_id}>"52 assert repr(func) != f"<{start_str} {id_}>"53 assert repr(func) != f"<{start_str} {func_id}>"54 func = cure.decorator()(wrapped_func)55 assert str(func) != f"<{start_str} {id_}>"56 assert str(func) != f"<{start_str} {func_id}>"57 assert repr(func) != f"<{start_str} {id_}>"...
Using AI Code Generation
1import { addDecorator } from '@storybook/react';2import { withRoot } from 'storybook-root-decorator';3import { withKnobs } from '@storybook/addon-knobs';4import { withInfo } from '@storybook/addon-info';5addDecorator(withRoot);6addDecorator(withKnobs);7addDecorator(withInfo);8import { configure, addDecorator } from '@storybook/react';9import { withRoot } from 'storybook-root-decorator';10import { withKnobs } from '@storybook/addon-knobs';11import { withInfo } from '@storybook/addon-info';12addDecorator(withRoot);13addDecorator(withKnobs);14addDecorator(withInfo);15import '@storybook/addon-actions/register';16import '@storybook/addon-links/register';17import '@storybook/addon-knobs/register';18import '@storybook/addon-info/register';19import 'storybook-root-decorator/register';20import { withRoot } from 'storybook-root-decorator';21import { withKnobs } from '@storybook/addon-knobs';22import { withInfo } from '@storybook/addon-info';23export const decorators = [withRoot, withKnobs, withInfo];24import { addons } from '@storybook/addons';25import { create } from '@storybook/theming';26addons.setConfig({27 theme: create({28 }),29});30const path = require('path');31module.exports = async ({ config, mode }) => {32 config.module.rules.push({33 include: path.resolve(__dirname, '../'),34 });35 return config;36};
Using AI Code Generation
1import { addDecorator } from '@storybook/react';2import { withRoot } from 'storybook-root-decorator';3addDecorator(withRoot);4import { addDecorator } from '@storybook/react';5import withRoot from 'storybook-root-decorator';6addDecorator(withRoot);7import { configure } from '@storybook/react';8const req = require.context('../src', true, /\.stories\.js$/);9function loadStories() {10 req.keys().forEach(filename => req(filename));11}12configure(loadStories, module);13module.exports = (baseConfig, env, defaultConfig) => {14 defaultConfig.module.rules.push({15 test: /\.(ts|tsx)$/,16 loader: require.resolve('awesome-typescript-loader'),17 });18 defaultConfig.resolve.extensions.push('.ts', '.tsx');19 return defaultConfig;20};21import '@storybook/addon-actions/register';22import '@storybook/addon-links/register';23import { configure, addDecorator } from '@storybook/react';24import { withInfo } from '@storybook/addon-info';25import { withKnobs } from '@storybook/addon-knobs';26import { withA11y } from '@storybook/addon-a11y';27addDecorator(withInfo);28addDecorator(withKnobs);29addDecorator(withA11y);30import { configure, addDecorator } from '@storybook/react';31import { withInfo } from '@storybook/addon-info';32import { withKnobs } from '@storybook/addon-knobs';33import { withA11y } from '@storybook/addon-a11y';34addDecorator(withInfo);35addDecorator(withKnobs);36addDecorator(withA11y);37import { configure, addDecorator } from '@storybook/react';38import { withInfo } from '@storybook/addon-info';39import { withKnobs } from '@storybook/addon-knobs';40import { withA11y } from '@storybook/addon-a11y';41addDecorator(withInfo);42addDecorator(withKnobs);43addDecorator(withA11y);44import {
Using AI Code Generation
1import { addDecorator } from "@storybook/react";2import withRootDecorator from "storybook-root-decorator";3addDecorator(withRootDecorator);4import { addDecorator } from "@storybook/react";5import { withThemesProvider } from "storybook-addon-styled-component-theme";6import themes from "./themes";7addDecorator(withThemesProvider(themes));8import { addDecorator } from "@storybook/react";9import { ThemeProvider } from "@material-ui/core/styles";10import { muiTheme } from "storybook-addon-material-ui";11import theme from "./theme";12addDecorator(muiTheme([theme]));13import { addDecorator } from "@storybook/react";14import { withThemesProvider } from "storybook-addon-styled-component-theme";15import themes from "./themes";16addDecorator(withThemesProvider(themes));17import { addDecorator } from "@storybook/react";18import { ThemeProvider } from "@material-ui/core/styles";19import { muiTheme } from "storybook-addon-material-ui";20import theme from "./theme";21addDecorator(muiTheme([theme]));22import { addDecorator } from "@storybook/react";23import { withThemesProvider } from "storybook-addon-styled-component-theme";24import themes from "./themes";25addDecorator(withThemesProvider(themes));26import { addDecorator } from "@storybook/react";27import { ThemeProvider } from "@material-ui/core/styles";28import { muiTheme } from "storybook-addon-material-ui";29import theme from "./theme";30addDecorator(muiTheme([theme]));
Using AI Code Generation
1import { addDecorator } from '@storybook/react';2import withRootDecorator from 'storybook-root-decorator';3addDecorator(withRootDecorator);4import { configure } from '@storybook/react';5import withRootDecorator from 'storybook-root-decorator';6addDecorator(withRootDecorator);7import { configure } from '@storybook/react';8import withRootDecorator from 'storybook-root-decorator';9addDecorator(withRootDecorator);10import { configure } from '@storybook/react';11import withRootDecorator from 'storybook-root-decorator';12addDecorator(withRootDecorator);13import { configure } from '@storybook/react';14import withRootDecorator from 'storybook-root-decorator';15addDecorator(withRootDecorator);16import { configure } from '@storybook/react';17import withRootDecorator from 'storybook-root-decorator';18addDecorator(withRootDecorator);19import { configure } from '@storybook/react';20import withRootDecorator from 'storybook-root-decorator';21addDecorator(withRootDecorator);22import { configure } from '@storybook/react';23import withRootDecorator from 'storybook-root-decorator';24addDecorator(withRootDecorator);25import { configure } from '@storybook/react';26import withRootDecorator from 'storybook-root-decorator';
Using AI Code Generation
1import { addDecorator } from '@storybook/react';2import withRootDecorator from 'storybook-root-decorator';3addDecorator(withRootDecorator);4import { addDecorator } from '@storybook/react';5import withRootDecorator from 'storybook-root-decorator';6addDecorator(withRootDecorator);7import { addDecorator } from '@storybook/react';8import withRootDecorator from 'storybook-root-decorator';9addDecorator(withRootDecorator);
Using AI Code Generation
1import { withRootDecorator } from 'storybook-root-decorator';2import { addDecorator } from '@storybook/react';3addDecorator(withRootDecorator);4import { withRootDecorator } from 'storybook-root-decorator';5import { addDecorator } from '@storybook/react';6addDecorator(withRootDecorator);7import { withRootDecorator } from 'storybook-root-decorator';8import { addDecorator } from '@storybook/react';9addDecorator(withRootDecorator);10import { withRootDecorator } from 'storybook-root-decorator';11import { addDecorator } from '@storybook/react';12addDecorator(withRootDecorator);13MIT © [Siddharth Bhanushali](
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!