This will offer a step by step guide to create a new run in TestRail,
        update tests in the run with results, and close the run
779817
def main():
    
    # Parse command line arguments
    args = get_args()

    # Instantiate the TestRail client
    # Use the CLI argument to identify which project to work with
    tr = TestRail(project_dict[args.project])

    # Get a reference to the current project
    project = tr.project(project_dict[args.project])

    # To create a new run in TestRail, first create a new, blank run
    # Update the new run with a name and project reference
    new_run = tr.run()
    new_run.name = "Creating a new Run through the API"
    new_run.project = project
    new_run.include_all = True  # All Cases in the Suite will be added as Tests

    # Add the run in TestRail. This creates the run, and returns a run object
    run = tr.add(new_run)

    print("Created new run: {0}".format(run.name))

    # Before starting the tests, lets pull in the Status objects for later
    PASSED = tr.status('passed')
    FAILED = tr.status('failed')
    BLOCKED = tr.status('blocked')

    # Get a list of tests associated with the new run
    tests = list(tr.tests(run))

    print("Found {0} tests".format(len(tests)))

    # Execute the tests, marking as passed, failed, or blocked
    for test_num, test in enumerate(tests):
        print("Executing test #{0}".format(test_num))
        # Run your tests here, reaching some sort of pass/fail criteria
        # This example will pick results at random and update the tests as such

        test_status = random.choice([PASSED, FAILED, BLOCKED])

        print("Updating test  #{0} with a status of {1}".format(test_num,
                                                               test_status.name))

        # Create a blank result, and associate it with a test and a status
        result = tr.result()
        result.test = test
        result.status = test_status
        result.comment = "The test case was udpated via a script"

        # Add the result to TestRail
        tr.add(result)

    # All tests have been executed. Close this test run
    print("Finished, closing the run")
    tr.close(run)
1144905
public final void run()
   {
      try
      {
         copy( this.is, this.os );
      }
      catch ( IOException ioe )
      {
         log.error(ioe);
      }
      finally
      {
         try
         {
            this.is.close();
         }
         catch (IOException ioe)
         {
            log.error(ioe);
         }
         if (this.closeOsOnExit)
         {
            try
            {
               this.os.flush();
               this.os.close();
            }
            catch (IOException ioe)
            {
               log.error(ioe);
            }
         }
      }
   }
786735
def run_task
      config = create_configuration
      runner = RubyLint::Runner.new(config)
      list   = FileList.new
      output = runner.analyze(list.process(files))

      puts(output) unless output.empty?
    end
240079
function(testPath) {
    var testStartTime = +new Date();

    var waitForTest = function(resolve, reject) {
      // executeScript runs the passed method in the "window" context of
      // the current test. JSUnit exposes hooks into the test's status through
      // the "G_testRunner" global object.
      browser
          .executeScript(function() {
            if (window['G_testRunner'] &&
                window['G_testRunner']['isFinished']()) {
              var status = {};
              status['isFinished'] = true;
              status['isSuccess'] = window['G_testRunner']['isSuccess']();
              status['report'] = window['G_testRunner']['getReport']();
              return status;
            } else {
              return {'isFinished': false};
            }
          })
          .then(
              function(status) {
                if (status && status.isFinished) {
                  resolve(status);
                } else {
                  var currTime = +new Date();
                  if (currTime - testStartTime > TEST_TIMEOUT) {
                    status.isSuccess = false;
                    status.report = testPath + ' timed out after ' +
                        (TEST_TIMEOUT / 1000) + 's!';
                    // resolve so tests continue running.
                    resolve(status);
                  } else {
                    // Check every 300ms for completion.
                    setTimeout(
                        waitForTest.bind(undefined, resolve, reject), 300);
                  }
                }
              },
              function(err) {
                reject(err);
              });
    };

    return new Promise(function(resolve, reject) {
      waitForTest(resolve, reject);
    });
  }
1204675
def run_on_changes(paths)
      specs = Inspector.clean(paths)
      return false if specs.empty?

      specs += self.rerun_specs if options[:keep_failed]

      # RSpec reloads the files, so reload only non spec files
      (paths - specs).each { |path| Reloader.reload_file(path) }

      passed, failed_examples, passed_examples = Runner.run(specs, options)

      self.rerun_specs += failed_examples
      self.rerun_specs -= passed_examples

      run_all if passed && !self.last_run_passed && options[:all_after_pass]

      self.last_run_passed = passed

      throw :task_has_failed unless passed
    end
965716
function runWithAfter (ret, runWith) {
    // after original promise resolves then run after methods
    return ret.then(res => {
        // wait for all extension methods to complete
        return Promise.all(runWith)
        // merge returned data into original
        .then(function (results) {
            // either merge or replace result
            _.each(results, result => {
                // both original res and after result are objects
                if (typeof res === 'object' && res !== null && typeof result === 'object' && result !== null) {
                    // merge after into original
                    _.merge(res, result)
                }
                // one is not an object
                else if (result !== undefined) {
                    // replace original with after
                    res = result
                }
            })
            // return final result
            return res
        })
    })
}
238928
def run_all
      return pending_result unless test_paths?
      Guard::UI.info("Resetting", reset: true)
      do_run{ @runner.run(@test_paths) }
    end
463028
function done() {
  	var storage = config.storage;

  	ProcessingQueue.finished = true;

  	var runtime = now() - config.started;
  	var passed = config.stats.all - config.stats.bad;

  	emit("runEnd", globalSuite.end(true));
  	runLoggingCallbacks("done", {
  		passed: passed,
  		failed: config.stats.bad,
  		total: config.stats.all,
  		runtime: runtime
  	});

  	// Clear own storage items if all tests passed
  	if (storage && config.stats.bad === 0) {
  		for (var i = storage.length - 1; i >= 0; i--) {
  			var key = storage.key(i);

  			if (key.indexOf("qunit-test-") === 0) {
  				storage.removeItem(key);
  			}
  		}
  	}
  }
455302
function(runs, suites, tests, coverages, logs) {
    debug('setting up Mocha command line reporter');

    runs.on('error', this.proxy('error'));

    runs.on('created', this.proxy('startRun'));
    runs.on('patched', this.proxy('updateRun'));

    suites.on('created', this.proxy('startSuite'));
    suites.on('patched', this.proxy('updateSuite'));

    tests.on('created', this.proxy('startTest'));
    tests.on('patched', this.proxy('updateTest'));

    logs.on('created', this.proxy('captureLog'));

    coverages.on('created', this.proxy('reportCoverage'));

    this.start();
  }
501825
function Progress(runner, options) {
  Base.call(this, runner, options);

  var self = this;
  var width = (Base.window.width * 0.5) | 0;
  var total = runner.total;
  var complete = 0;
  var lastN = -1;

  // default chars
  options = options || {};
  var reporterOptions = options.reporterOptions || {};

  options.open = reporterOptions.open || '[';
  options.complete = reporterOptions.complete || '▬';
  options.incomplete = reporterOptions.incomplete || Base.symbols.dot;
  options.close = reporterOptions.close || ']';
  options.verbose = reporterOptions.verbose || false;

  // tests started
  runner.on(EVENT_RUN_BEGIN, function() {
    console.log();
    cursor.hide();
  });

  // tests complete
  runner.on(EVENT_TEST_END, function() {
    complete++;

    var percent = complete / total;
    var n = (width * percent) | 0;
    var i = width - n;

    if (n === lastN && !options.verbose) {
      // Don't re-render the line if it hasn't changed
      return;
    }
    lastN = n;

    cursor.CR();
    process.stdout.write('\u001b[J');
    process.stdout.write(color('progress', '  ' + options.open));
    process.stdout.write(Array(n).join(options.complete));
    process.stdout.write(Array(i).join(options.incomplete));
    process.stdout.write(color('progress', options.close));
    if (options.verbose) {
      process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
    }
  });

  // tests are complete, output some stats
  // and the failures if any
  runner.once(EVENT_RUN_END, function() {
    cursor.show();
    console.log();
    self.epilogue();
  });
}
1093823
function JSONReporter(runner, options) {
  Base.call(this, runner, options);

  var self = this;
  var tests = [];
  var pending = [];
  var failures = [];
  var passes = [];

  runner.on(EVENT_TEST_END, function(test) {
    tests.push(test);
  });

  runner.on(EVENT_TEST_PASS, function(test) {
    passes.push(test);
  });

  runner.on(EVENT_TEST_FAIL, function(test) {
    failures.push(test);
  });

  runner.on(EVENT_TEST_PENDING, function(test) {
    pending.push(test);
  });

  runner.once(EVENT_RUN_END, function() {
    var obj = {
      stats: self.stats,
      tests: tests.map(clean),
      pending: pending.map(clean),
      failures: failures.map(clean),
      passes: passes.map(clean)
    };

    runner.testResults = obj;

    process.stdout.write(JSON.stringify(obj, null, 2));
  });
}
494647
def run_on_changes(paths)
      paths += @failed_paths if @options[:keep_failed]
      paths = @inspector.clean(paths).uniq

      if passed = @runner.run(paths)
        remove_failed(paths)

        # run all the specs if the run before this one failed
        if @last_failed && @options[:all_after_pass]
          @last_failed = false
          run_all
        end
      else
        @last_failed = true
        add_failed(paths)

        throw :task_has_failed
      end
    end
38870
def start(args=[])
      # minitest changed #run in 6023c879cf3d5169953e on April 6th, 2011
      if ::MiniTest::Unit.respond_to?(:runner=)
        ::MiniTest::Unit.runner = self
      end
      # FIXME: why isn't @test_count set?
      run(args)
      return @turn_suite
    end
913926
def run!
      project.mode = :release

      # Validate paths
      validate_paths!

      # Extract mockup
      copy_source_path_to_build_path!

      validate_stack!

      # Run stack
      run_stack!

      # Cleanup
      cleanup! if config[:cleanup_build]
    ensure
      project.mode = nil
    end
862309
function(test) {
			var context = this.loopContext;
			var forkContext = this.forkContext;

			context.test = test;

			// Creates paths of `continue` statements.
			if (!context.continueForkContext.empty) {
				context.continueForkContext.add(forkContext.head);
				var testSegments = context.continueForkContext.makeNext(0, -1);

				forkContext.replaceHead(testSegments);
			}
		}
1290510
def run(**kwargs):
    """"""
    paths = kwargs.pop('paths', ())
    action = kwargs.pop('action')
    plugin = kwargs.pop('plugin')
    junit_xml = kwargs.pop('junit_xml')
    use_tracked_files = kwargs.pop('use_tracked_files')
    quiet = kwargs.pop('quiet')

    colorama.init(strip=kwargs.pop('no_color'))

    git_dir = current_git_dir()

    if git_dir is None:
        output(NOT_GIT_REPO_MSG)
        exit(1)

    repo_root = os.path.dirname(git_dir)

    files = []
    if paths:
        # We want to look at files in their current state if paths are passed through
        kwargs['include_unstaged_changes'] = True

        # If paths were provided get all the files for each path
        for path in paths:
            for f in list_files(path):
                f = os.path.relpath(f, repo_root)
                if not f.startswith('..'):  # Don't include files outside the repo root.
                    files.append(f)
    elif use_tracked_files:
        # If the use tracked files flag was passed, get a list of all the tracked files
        out, err, code = git.ls_files()
        files = out.splitlines()

        if kwargs.get('include_untracked'):
            out, err, code = git.ls_files(o=True, exclude_standard=True)
            files += out.splitlines()

    if files or paths:
        kwargs['files'] = files

    config = get_config(repo_root)
    runner = Runner(config.cwd, **kwargs)
    results = ResultCollection()

    if runner.unstaged_changes and not quiet:
        output(UNSTAGED_CHANGES_MSG, end='\n\n')

    processes = list(config.actions) + list(config.plugins)
    processes.sort(key=lambda x: x.name)  # Sort the list of processes for consistent results

    if plugin:
        try:
            processes = [config.plugins.get(plugin)]
        except config.plugins.DoesNotExist as e:
            output('{}\nAvailable plugins:'.format(e.message))

            for p in config.plugins:
                output(p.name)
            exit(1)

    if action:
        try:
            processes = [config.actions.get(action)]
        except config.actions.DoesNotExist as e:
            output('{}\nAvailable actions:'.format(e.message))

            for a in config.actions:
                output(a.name)
            exit(1)

    for process in processes:
        result, message = runner.run_process(process)
        results.append(result)

        if not quiet:
            output(message)

    if junit_xml:
        with open(junit_xml, 'w+') as f:
            f.write('{}'.format(results.dump_junit()))

    if not quiet:
        output(results.dump())
        output('#{{bright}}{}\nCompleted in: {}s'.format(''.ljust(79, '-'), round(results.execution_time, 2)))

    if results.has_error:
        exit(1)
    elif results.has_failure:
        exit(2)
877139
def begin(self):
        
        self.url = self.server.wiki.create(self)
        if not self.testmode:
            self.commit.create_status("pending", self.url, "Running unit tests...")