Best JavaScript code snippet using mountebank
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
1var mb = require('mountebank'),2    assert = require('assert');3mb.start({4}, function () {5    var imposter = mb.createImposter({6        stubs: [{7            predicates: [{8                equals: { method: 'GET', path: '/' }9            }],10            responses: [{11                is: { body: 'Hello from mountebank!' }12            }]13        }]14    });15    imposter.post(function (error, result) {16        assert.ifError(error);17        assert.equal(result.statusCode, 201);18        assert.deepEqual(result.body, { port: 4545 });19        console.log('Imposter created');20    });21});22var mb = require('mountebank'),23    assert = require('assert');24mb.start({25}, function () {26    var imposter = mb.createImposter({27        stubs: [{28            predicates: [{29                equals: { method: 'GET', path: '/' }30            }],31            responses: [{32                is: { body: 'Hello from mountebank!' }33            }]34        }]35    });36    imposter.post(function (error, result) {37        assert.ifError(error);38        assert.equal(result.statusCode, 201);39        assert.deepEqual(result.body, { port: 4545 });40        console.log('Imposter created');41    });42});43var mb = require('mountebank'),44    assert = require('assert');45mb.start({46}, function () {47    var imposter = mb.createImposter({48        stubs: [{49            predicates: [{50                equals: { method: 'Using AI Code Generation
1const mb = require('mountebank');2const imposter = {3        {4                {5                    is: {6                        headers: {7                        },8                    }9                }10        }11};12mb.create(imposter).then(function (server) {13});14mb.create(imposter, [options])15mb.createTcpServer(imposter, [options])Using AI Code Generation
1var mb = require('mountebank');2mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, server) {3    if (error) {4        console.error(error);5    } else {6        console.log('server created');7    }8});9mb.start({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, server) {10    if (error) {11        console.error(error);12    } else {13        console.log('server started');14    }15});16mb.stop({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, server) {17    if (error) {18        console.error(error);19    } else {20        console.log('server stopped');21    }22});23mb.del({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, server) {24    if (error) {25        console.error(error);26    } else {27        console.log('server deleted');28    }29});30mb.reset({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, server) {31    if (error) {32        console.error(error);33    } else {34        console.log('server reset');35    }36});37mb.put({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, server) {38    if (error) {39        console.error(error);40    } else {41        console.log('server put');42    }43});44mb.get({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, server) {45    if (error) {46        console.error(error);47    } else {48        console.log('server get');49    }50});51mb.post({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' }, function (error, server) {52    if (error) {53        console.error(error);54    } else {Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create();3imposter.addStub({4        {5            is: {6                headers: {7                },8            }9        }10});11imposter.addDecorator({12        {13            matches: {14            },15            generates: {16            }17        }18});19imposter.addDecorator({20        {21            matches: {22            },23            generates: {24            }25        }26});27imposter.addDecorator({28        {29            matches: {30            },31            generates: {32                query: {33                }34            }35        }36});37imposter.addDecorator({38        {39            matches: {40            },41            generates: {42                headers: {43                }44            }45        }46});47imposter.addDecorator({48        {49            matches: {50            },51            generates: {52            }53        }54});55imposter.addDecorator({56        {57            matches: {58            },59            generates: {60                cookies: {61                }62            }63        }64});65imposter.addDecorator({66        {67            matches: {68            },69            generates: {Using AI Code Generation
1var mb = require('mountebank');2mb.create({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, mb) {3  if (error) {4    console.error('Failed to start mb', error);5  } else {6    console.log('mb is running on port', mb.port);7  }8});9var mb = require('mountebank');10mb.create({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, mb) {11  if (error) {12    console.error('Failed to start mb', error);13  } else {14    console.log('mb is running on port', mb.port);15  }16});17var mb = require('mountebank');18mb.create({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, mb) {19  if (error) {20    console.error('Failed to start mb', error);21  } else {22    console.log('mb is running on port', mb.port);23  }24});25var mb = require('mountebank');26mb.create({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, mb) {27  if (error) {28    console.error('Failed to start mb', error);29  } else {30    console.log('mb is running on port', mb.port);31  }32});33var mb = require('mountebank');34mb.create({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, mb) {35  if (error) {36    console.error('Failed to start mb', error);37  } else {38    console.log('mb is running on port', mb.port);39  }40});41var mb = require('mountebank');42mb.create({port: 2525, pidfile: 'mb.pid', logfile: 'Using AI Code Generation
1var mb = require('mountebank');2var assert = require('assert');3var Q = require('q');4var port = 2525;5var protocol = 'http';6var host = 'localhost';7var request = require('request');8function requestDecorator(method, path, data) {9    var deferred = Q.defer();10    var options = {11    };12    if (data) {13        options.body = data;14    }15    request(options, function (error, response, body) {16        if (error) {17            deferred.reject(error);18        } else {19            deferred.resolve(body);20        }21    });22    return deferred.promise;23}24var stub = {25    predicates: [{equals: {'path': '/test'}}],26    responses: [{is: {'statusCode': 200, 'body': 'Hello World'}}]27};28var imposter = {port: 4545, protocol: 'http', stubs: [stub]};29mb.create({port: port, pidfile: 'mb.pid', logfile: 'mb.log', loglevel: 'debug'})30    .then(function () {31        return requestDecorator('POST', '/imposters', imposter);32    })33    .then(function (response) {34        assert.strictEqual(response.port, imposter.port);35        assert.strictEqual(response.protocol, imposter.protocol);36        return requestDecorator('GET', '/imposters/' + imposter.port + '/requests');37    })38    .then(function (requests) {39        assert.strictEqual(requests.length, 1);40        assert.strictEqual(requests[0].request.path, '/test');41        return requestDecorator('DELETE', '/imposters/' + imposter.port);42    })43    .then(function () {44        return requestDecorator('GET', '/imposters/' + imposter.port);45    })46    .done(function (response) {47        assert.strictEqual(response.error, 'invalid imposter port');48        mb.stop();49    });Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const imposterPort = 3000;4const imposterProtocol = 'http';5const stubs = require('./stubs.json');6const imposters = {7};8const mbHelper = mb.create(port, imposters);9mbHelper.start().then(() => {10    console.log('mountebank started');11    mbHelper.get('/').then((response) => {12        console.log('response from mountebank', response.body);13        mbHelper.stop().then(() => {14            console.log('mountebank stopped');15        });16    });17});18    {19            {20                "is": {21                    "headers": {22                    },23                    "body": {24                    }25                }26            }27    }Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create();3imposter.addDecorator(function (req, res) {4    res.headers['X-Test'] = 'test';5});6imposter.addStub({7    predicates: [{ equals: { path: '/test' } }],8    responses: [{ is: { body: 'test' } }]9});10imposter.addStub({11    predicates: [{ equals: { path: '/test2' } }],12    responses: [{ is: { body: 'test2' } }]13});14imposter.addStub({15    predicates: [{ equals: { path: '/test3' } }],16    responses: [{ is: { body: 'test3' } }]17});18imposter.addStub({19    predicates: [{ equals: { path: '/test4' } }],20    responses: [{ is: { body: 'test4' } }]21});22imposter.addStub({23    predicates: [{ equals: { path: '/test5' } }],24    responses: [{ is: { body: 'test5' } }]25});26imposter.addStub({27    predicates: [{ equals: { path: '/test6' } }],28    responses: [{ is: { body: 'test6' } }]29});30imposter.addStub({31    predicates: [{ equals: { path: '/test7' } }],32    responses: [{ is: { body: 'test7' } }]33});34imposter.addStub({35    predicates: [{ equals: { path: '/test8' } }],36    responses: [{ is: { body: 'test8' } }]37});38imposter.addStub({39    predicates: [{ equals: { path: '/test9' } }],40    responses: [{ is: { body: 'test9' } }]41});42imposter.addStub({43    predicates: [{ equals: { path: '/test10' } }],44    responses: [{ is: { body: 'test10' } }]45});46imposter.addStub({47    predicates: [{ equals: { path: '/test11' } }],48    responses: [{ is: { body: 'test11' } }]49});50imposter.addStub({51    predicates: [{ equals: { path: '/test12' } }],52    responses: [{ is: { body: 'test12' } }]53});54imposter.addStub({55    predicates: [{ equals: { path: '/test13' } }],56    responses: [{ is: { bodyUsing AI Code Generation
1const { createDecorator } = require('mountebank');2const decorator = createDecorator();3const response = {4    headers: {5    },6    body: {7    }8};9module.exports = {10        {11                {12                        decorator.json(response)13                }14        }15};16const { createDecorator } = require('mountebank');17const decorator = createDecorator();18const response = {19    headers: {20    },21    body: {22    }23};24module.exports = {25        {26                {27                        decorator.json(response)28                }29        }30};31const { createDecorator } = require('mountebank');32const decorator = createDecorator();33const response = {34    headers: {35    },36    body: {37    }38};39module.exports = {40        {41                {42                        decorator.json(response)43                }44        }45};46const { createDecorator } = require('mountebank');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!!
