Returns a function that adds fixtures handling to the teardown method.

        Calls the given teardown method first before calling the fixtures teardown.
357635
def teardown_handler(teardown_fixtures_fn, teardown_fn):
        
        def handler(obj):
            teardown_fn(obj)
            teardown_fixtures_fn(obj)
        return handler
21382
def call_only_once(func):
    
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        # cannot use hasattr here, because hasattr tries to getattr, which
        # fails if func is a property
        assert func.__name__ in dir(self), "call_only_once can only be used on method or property!"

        if not hasattr(self, '_CALL_ONLY_ONCE_CACHE'):
            cache = self._CALL_ONLY_ONCE_CACHE = set()
        else:
            cache = self._CALL_ONLY_ONCE_CACHE

        cls = type(self)
        # cannot use ismethod(), because decorated method becomes a function
        is_method = inspect.isfunction(getattr(cls, func.__name__))
        assert func not in cache, \
            "{} {}.{} can only be called once per object!".format(
                'Method' if is_method else 'Property',
                cls.__name__, func.__name__)
        cache.add(func)

        return func(*args, **kwargs)

    return wrapper
1366039
def _enable_cleanup(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        result = func(*args, **kwargs)
        self.cleanup(self)
        return result

    return wrapper
78399
function wrapMutatingArrayMethod(method, func) {
      return function() {
        var result = [][method].apply(obj, arguments);
        this.len = this.values.length;
        cache = {};
        children = {};
        func.apply(this, arguments);
        target.parent.trigger('update', target.prop);
        return result;
      };
    }
673912
function tearDownPage() {
         visibilityManager.unsubscribe();
         localeManager.unsubscribe();

         publishDebugInfo( 'willUnload.page', { page: activePage } );

         return eventBus
            .publishAndGatherReplies( 'endLifecycleRequest.default', LIFECYCLE_EVENT, EVENT_OPTIONS )
            .then( () => {
               const pageName = activePage;
               activeWidgetAdapterWrappers.forEach( wrapper => wrapper.destroy() );
               activeWidgetAdapterWrappers = [];
               activePage = null;

               publishDebugInfo( 'didUnload.page', { page: pageName } );
               cleanUpLayout();
               cleanUpLayout = () => {};
            } );
      }
594173
def as_fixture(self, name=None):
        
        if name is None:
            name = self.name

        def deco(f):
            @functools.wraps(f)
            def wrapper(*args, **kw):
                with self:
                    kw[name] = self
                    return f(*args, **kw)
            return wrapper
        return deco
297992
private Scope getMethodScope(boolean isDestroy, Method method) {
        Scope methodScope;
        if ( isDestroy ) {
            Destroy annotation = method.getAnnotation(Destroy.class);
            methodScope = annotation != null ? annotation.scope() : null;
        } else {
            Initialize annotation = method.getAnnotation(Initialize.class);
            methodScope = annotation != null ? annotation.scope() : null;
        }
        return methodScope;
    }
567142
function(error, method) {
    queued++;
    if (typeof wipe[method] == 'function') {
      wipe[method](function(err, removed) {
        if (err) last_err = err;

        removed += removed;
        --queued || finished(last_err);
      })
    } else return finished(error);
  }
702865
public function tearDownMockery()
    {
        if (class_exists(Mockery::class, false)) {
            $container = Mockery::getContainer();

            if ($container) {
                $this->addToAssertionCount($container->mockery_getExpectationCount());
            }

            Mockery::close();
        }
    }
1286061
public function teardown(
        ExampleNode $example,
        Specification $context,
        MatcherManager $matchers,
        CollaboratorManager $collaborators
    ) {
    
        return $this;
    }
839810
function(callbacks, context){
      // avoid warnings on trying to remove handler for destroyed instance
      // since it droped all handlers
      if (this.destroy === warnOnDestroy)
        return;

      var cursor = this;
      var prev;

      context = context || this;

      // search for handler and remove it
      while (prev = cursor, cursor = cursor.handler)
        if (cursor.callbacks === callbacks && cursor.context === context)
        {
          // make it non-callable
          cursor.callbacks = NULL_HANDLER;

          // remove from list
          prev.handler = cursor.handler;

          return;
        }

      // handler not found
      /** @cut */ basis.dev.warn(namespace + '.Emitter#removeHandler: no handler removed');
    }
717838
function addShutdown(server) {
  var connections = {};
  var isShuttingDown = false;
  var connectionCounter = 0;

  function destroy(socket, force) {
    if (force || (socket._isIdle && isShuttingDown)) {
      socket.destroy();
      delete connections[socket._connectionId];
    }
  };

  function onConnection(socket) {
    var id = connectionCounter++;
    socket._isIdle = true;
    socket._connectionId = id;
    connections[id] = socket;

    socket.on('close', function() {
      delete connections[id];
    });
  };

  server.on('request', function(req, res) {
    req.socket._isIdle = false;

    res.on('finish', function() {
      req.socket._isIdle = true;
      destroy(req.socket);
    });
  });

  server.on('connection', onConnection);
  server.on('secureConnection', onConnection);

  function shutdown(force, cb) {
    isShuttingDown = true;
    server.close(function(err) {
      if (cb) {
        process.nextTick(function() { cb(err); });
      }
    });

    Object.keys(connections).forEach(function(key) {
      destroy(connections[key], force);
    });
  };

  server.shutdown = function(cb) {
    shutdown(false, cb);
  };

  server.forceShutdown = function(cb) {
    shutdown(true, cb);
  };

  return server;
}
297911
function teardown() {

  var audits = [];

  if (this.config.axe) {
    audits.push(runAxe(this));
  }

  if (this.config.chromeA11YDevTools) {
    audits.push(runChromeDevTools(this));
  }
  // check for Tenon config and an actual API key, not the placeholder
  if (this.config.tenonIO && /[A-Za-z][0-9]/.test(
      this.config.tenonIO.options.key)) {
    audits.push(runTenonIO(this));
  }
  return q.all(audits);
}
239279
function() {
        var FN_ARGS        = /^function\s*[^\(]*\(\s*([^\)]*)\)/m,
            FN_ARG_SPLIT   = /,/,
            FN_ARG         = /^\s*(_?)(\S+?)\1\s*$/,
            STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
            getParams      = function(fn) {
                var fnText, argDecl;
                var args = [];
                fnText = fn.toString().replace(STRIP_COMMENTS, '');
                argDecl = fnText.match(FN_ARGS);

                var r = argDecl[1].split(FN_ARG_SPLIT), repl = function(all, underscore, name) {
                    args.push(name);
                };
                for (var a in r) {
                    var arg = r[a];
                    arg.replace(FN_ARG, repl);
                }

                return args;
            };

        var prototype = this.reflector.getProto();
        var overloads = prototype.__joii__.metadata[this.name].overloads;

        if (!overloads || overloads.length === 0) {
            // old method for BC (wasn't recognized as a function when prototyping)
            return getParams(this.reflector.getProto()[this.name]);
        } else if (overloads.length === 1 && overloads[0].parameters.length === 0) {
            // old method for BC (was recognized when prototyping, but old style)
            return getParams(overloads[0].fn);
        }
        else {
            var ret = [];

            for (var idx = 0; idx < overloads.length; idx++) {
                var fn_meta = [];
                var function_parameters_meta = overloads[idx];
                var parsed_params = getParams(function_parameters_meta.fn);
                for (var j = 0; j < function_parameters_meta.parameters.length; j++) {
                    var param = {
                        name: parsed_params.length > j ? parsed_params[j] : null,
                        type: function_parameters_meta.parameters[j]
                    };
                    fn_meta.push(param);
                }
                ret.push(fn_meta);
            }
            return ret;
        }
    }
51737
def enhance_method(method, callbacks)
      _method = (PREFIX + method.to_s).to_sym
      alias_method _method, method

      self.send(:define_method, method) do |*args, &blk|
        [callbacks, _method].flatten.each do |callback|
          break unless self.send(callback, *args, &blk)
        end
      end
    end
1159213
function wrap(method) {
            return function() {
                // cast any arguments into an array, since they're
                // natively objects
                var args = Array.prototype.slice.apply(arguments);
                // make the first argument the array itself
                args.unshift(this);
                // return the result of the ss method
                return ss[method].apply(ss, args);
            };
        }
854478
def tearDown(self):
        
        has_exception = False
        if sys.version.startswith('3') and hasattr(self, '_outcome'):
            if hasattr(self._outcome, 'errors') and self._outcome.errors:
                has_exception = True
        else:
            has_exception = sys.exc_info()[1] is not None
        if self.__delayed_assert_failures:
            print(
                "\nWhen using self.delayed_assert_*() methods in your tests, "
                "remember to call self.process_delayed_asserts() afterwards. "
                "Now calling in tearDown()...\nFailures Detected:")
            if not has_exception:
                self.process_delayed_asserts()
            else:
                self.process_delayed_asserts(print_only=True)
        self.is_pytest = None
        try:
            # This raises an exception if the test is not coming from pytest
            self.is_pytest = sb_config.is_pytest
        except Exception:
            # Not using pytest (probably nosetests)
            self.is_pytest = False
        if self.is_pytest:
            # pytest-specific code
            test_id = "%s.%s.%s" % (self.__class__.__module__,
                                    self.__class__.__name__,
                                    self._testMethodName)
            try:
                with_selenium = self.with_selenium
            except Exception:
                sub_class_name = str(
                    self.__class__.__bases__[0]).split('.')[-1].split("'")[0]
                sub_file_name = str(self.__class__.__bases__[0]).split('.')[-2]
                sub_file_name = sub_file_name + ".py"
                class_name = str(self.__class__).split('.')[-1].split("'")[0]
                file_name = str(self.__class__).split('.')[-2] + ".py"
                class_name_used = sub_class_name
                file_name_used = sub_file_name
                if sub_class_name == "BaseCase":
                    class_name_used = class_name
                    file_name_used = file_name
                fix_setup = "super(%s, self).setUp()" % class_name_used
                fix_teardown = "super(%s, self).tearDown()" % class_name_used
                message = ("You're overriding SeleniumBase's BaseCase setUp() "
                           "method with your own setUp() method, which breaks "
                           "SeleniumBase. You can fix this by going to your "
                           "%s class located in your %s file and adding the "
                           "following line of code AT THE BEGINNING of your "
                           "setUp() method:\n%s\n\nAlso make sure "
                           "you have added the following line of code AT THE "
                           "END of your tearDown() method:\n%s\n"
                           % (class_name_used, file_name_used,
                              fix_setup, fix_teardown))
                raise Exception(message)
            if with_selenium:
                # Save a screenshot if logging is on when an exception occurs
                if has_exception:
                    self.__add_pytest_html_extra()
                if self.with_testing_base and not has_exception and (
                        self.save_screenshot_after_test):
                    test_logpath = self.log_path + "/" + test_id
                    if not os.path.exists(test_logpath):
                        try:
                            os.makedirs(test_logpath)
                        except Exception:
                            pass  # Only reachable during multi-threaded runs
                    if not self.__last_page_screenshot_png:
                        self.__set_last_page_screenshot()
                    log_helper.log_screenshot(
                        test_logpath,
                        self.driver,
                        self.__last_page_screenshot_png)
                    self.__add_pytest_html_extra()
                if self.with_testing_base and has_exception:
                    test_logpath = self.log_path + "/" + test_id
                    if not os.path.exists(test_logpath):
                        try:
                            os.makedirs(test_logpath)
                        except Exception:
                            pass  # Only reachable during multi-threaded runs
                    if ((not self.with_screen_shots) and (
                            not self.with_basic_test_info) and (
                            not self.with_page_source)):
                        # Log everything if nothing specified (if testing_base)
                        if not self.__last_page_screenshot_png:
                            self.__set_last_page_screenshot()
                        log_helper.log_screenshot(
                            test_logpath,
                            self.driver,
                            self.__last_page_screenshot_png)
                        log_helper.log_test_failure_data(
                            self, test_logpath, self.driver, self.browser)
                        log_helper.log_page_source(test_logpath, self.driver)
                    else:
                        if self.with_screen_shots:
                            if not self.__last_page_screenshot_png:
                                self.__set_last_page_screenshot()
                            log_helper.log_screenshot(
                                test_logpath,
                                self.driver,
                                self.__last_page_screenshot_png)
                        if self.with_basic_test_info:
                            log_helper.log_test_failure_data(
                                self, test_logpath, self.driver, self.browser)
                        if self.with_page_source:
                            log_helper.log_page_source(
                                test_logpath, self.driver)
                # (Pytest) Finally close all open browser windows
                self.__quit_all_drivers()
            if self.headless:
                if self.headless_active:
                    self.display.stop()
                    self.display = None
            if self.with_db_reporting:
                if has_exception:
                    self.__insert_test_result(constants.State.ERROR, True)
                else:
                    self.__insert_test_result(constants.State.PASS, False)
                runtime = int(time.time() * 1000) - self.execution_start_time
                self.testcase_manager.update_execution_data(
                    self.execution_guid, runtime)
            if self.with_s3_logging and has_exception:
                """ If enabled, upload logs to S3 during test exceptions. """
                from seleniumbase.core.s3_manager import S3LoggingBucket
                s3_bucket = S3LoggingBucket()
                guid = str(uuid.uuid4().hex)
                path = "%s/%s" % (self.log_path, test_id)
                uploaded_files = []
                for logfile in os.listdir(path):
                    logfile_name = "%s/%s/%s" % (guid,
                                                 test_id,
                                                 logfile.split(path)[-1])
                    s3_bucket.upload_file(logfile_name,
                                          "%s/%s" % (path, logfile))
                    uploaded_files.append(logfile_name)
                s3_bucket.save_uploaded_file_names(uploaded_files)
                index_file = s3_bucket.upload_index_file(test_id, guid)
                print("\n\n*** Log files uploaded: ***\n%s\n" % index_file)
                logging.error(
                    "\n\n*** Log files uploaded: ***\n%s\n" % index_file)
                if self.with_db_reporting:
                    self.testcase_manager = TestcaseManager(self.database_env)
                    data_payload = TestcaseDataPayload()
                    data_payload.guid = self.testcase_guid
                    data_payload.logURL = index_file
                    self.testcase_manager.update_testcase_log_url(data_payload)
        else:
            # (Nosetests)
            if has_exception:
                test_id = "%s.%s.%s" % (self.__class__.__module__,
                                        self.__class__.__name__,
                                        self._testMethodName)
                test_logpath = "latest_logs/" + test_id
                if not os.path.exists(test_logpath):
                    try:
                        os.makedirs(test_logpath)
                    except Exception:
                        pass  # Only reachable during multi-threaded runs
                log_helper.log_test_failure_data(
                    self, test_logpath, self.driver, self.browser)
                if len(self._drivers_list) > 0:
                    if not self.__last_page_screenshot_png:
                        self.__set_last_page_screenshot()
                    log_helper.log_screenshot(
                        test_logpath,
                        self.driver,
                        self.__last_page_screenshot_png)
                    log_helper.log_page_source(test_logpath, self.driver)
            elif self.save_screenshot_after_test:
                test_id = "%s.%s.%s" % (self.__class__.__module__,
                                        self.__class__.__name__,
                                        self._testMethodName)
                test_logpath = "latest_logs/" + test_id
                if not os.path.exists(test_logpath):
                    try:
                        os.makedirs(test_logpath)
                    except Exception:
                        pass  # Only reachable during multi-threaded runs
                if not self.__last_page_screenshot_png:
                    self.__set_last_page_screenshot()
                log_helper.log_screenshot(
                    test_logpath,
                    self.driver,
                    self.__last_page_screenshot_png)
            if self.report_on:
                self._last_page_screenshot = self.__last_page_screenshot_png
                try:
                    self._last_page_url = self.get_current_url()
                except Exception:
                    self._last_page_url = "(Error: Unknown URL)"
            # Finally close all open browser windows
            self.__quit_all_drivers()