コード例 #1
0
ファイル: baseaction.py プロジェクト: bigwheel/zaffy
  def debug_print(self, printer, index):
    debug = self._params.debug

    if not self._params.enable:
      printer.simple_write("skipped_action: {0}".format(index))

    if not debug:
      return

    if debug == True:
      debug = ["in", "out"]

    if isinstance(debug, util.basestring):
      debug_dict = {debug: debug}
    elif isinstance(debug, list):
      debug_dict = dict([(k, k) for k in debug])
    elif isinstance(debug, dict):
      debug_dict = debug
    else:
      debug_dict = {util.unicode(debug): util.unicode(debug)}

    variables = {}
    variables.update({
      "in": self.input,
      "out": self.output,
      "res": self.output,
      "this": self.__dict__
    })
    try:
      result = template.expand_param(debug_dict, variables)
      printer.write(result)
    except Exception as e:
      printer.write({"error": util.unicode(e)})
コード例 #2
0
ファイル: json_equal.py プロジェクト: bigwheel/zaffy
def is_json_equal(left_value, right_value):
  """ test `left_value` is equal to `right_value` as json

  `left_value` と `right_value` が json として等しいことをテストする

  .. code-block:: yaml

     - サンプルシナリオ

     - action: local
       x: '{"x":100,"y":200}'
       y: '{"y":200,"x":100}'
       assert:
         - local.x is json_equal local.y
  """
  left_str = util.unicode(left_value)
  right_str = util.unicode(right_value)

  if left_str == right_str:
    return True

  try:
    left_json = json.loads(left_str)
    right_json = json.loads(right_str)
    return left_json == right_json
  except ValueError:
    return False
コード例 #3
0
ファイル: console.py プロジェクト: bigwheel/zaffy
 def default(self, line):
     try:
         result = eval(line, self.global_env)
         sys.stdout.write(pformat(result, indent=2))
     except Exception as e:
         sys.stdout.write(util.unicode(e))
     sys.stdout.write("\n\n")
コード例 #4
0
ファイル: default.py プロジェクト: kaffepanna/plugin.audio.sr
def show_menu(url):
  doc = util.get_document_by_url(url)
  ul = util.get_elements_by_tag_class(doc, 'ul', 'channel')[0]
  lis = util.get_elements_by_tag(ul, 'li')
  if url == BASE_URL:
    addDir("Extra", EXTRA_URL, MODE_SHOW_MENU)
  for li in lis:
    a = util.get_elements_by_tag(li, 'a')[0]
    url = util.unicode(a.getAttribute('href'))
    title = util.unicode(util.get_node_text(a).strip())
    if li.getAttribute('class') == 'channel':
      url = urljoin(BASE_STREAM_URL, url.split("/")[-1])
      addLink(title, url)
    else:
      url = urljoin(BASE_URL, re.sub("^/", "", url))
      addDir(title, url, MODE_SHOW_MENU)

  xbmcplugin.endOfDirectory(handle = int(sys.argv[1]), cacheToDisc=True )
コード例 #5
0
ファイル: scenarioloader.py プロジェクト: bigwheel/zaffy
    def load(self, setting, parent=None):
        if setting.filename and parent:
            self._assert_no_circular_reference(setting.filename, parent)

        try:
            header, raw_actions = self.parse(setting.read())
        except Exception as e:
            raise ScenarioLoadError(setting.filename, e.__class__.__name__, util.unicode(e))
        return Scenario(setting, header, self.create_actions(raw_actions), parent)
コード例 #6
0
ファイル: scenariorunner.py プロジェクト: bigwheel/zaffy
 def _encode(self, exception):
   root = exception.root
   if isinstance(root.original, EnvironmentError):
     root.stack_trace = util.unicode_os_string(root.stack_trace)
   elif not isinstance(root.stack_trace, six.text_type):
     encoding = chardet.detect(root.stack_trace)
     if encoding['confidence'] > 0.95:
       root.stack_trace = util.unicode(root.stack_trace, encoding['encoding'])
   return exception
コード例 #7
0
ファイル: ini.py プロジェクト: bigwheel/zaffy
def do_asini(value):
  dummy_section = "__{0}__".format(id(value))
  value = "[{0}]\n".format(dummy_section) + value
  config = configparser.SafeConfigParser()
  config.readfp(io.StringIO(util.unicode(value)))

  if len(config.sections()) == 1:
    result = dict(config.items(dummy_section))
  else:
    config.remove_section(dummy_section)
    result = dict((section, dict(config.items(section))) for section in config.sections())
  return result
コード例 #8
0
ファイル: zaffy.py プロジェクト: bigwheel/zaffy
def run_scenario(global_env):
  formatter = global_env['formatter']
  failed = False
  try:
    agg = Aggregator()
    agg.add_filter(TagFilter(option.tags))
    agg.add_files(option.targets)
  except ScenarioLoadError as e:
    formatter.writer.write("{0}({1}):\n  {2}\n\n".format(e.__class__.__name__, e.error, e.filename))
    formatter.writer.write(util.unicode(e) + "\n")
    failed = True

  runner = ScenarioRunner(agg, formatter)
  failed = failed or runner.run(global_env)

  return int(failed)
コード例 #9
0
ファイル: shell.py プロジェクト: bigwheel/zaffy
  def do_run(self, cmd, stdin=None, curdir=None, shell=True, error_on_failed=False):
    """ コマンドの実行

    .. code-block:: yaml

     - サンプルシナリオ

     - action: shell
       cmd: ls -l /tmp

     - action: debug
       output: <<last.out.stdout>>

    :param string cmd: 実行するコマンド
    :param string curdir: 実行時のカレントディレクトリ。指定しない場合は zaffy 実行時のカレントディレクトリ
    :param bool shell: シェルを介して実行する (default:True)
    :param bool error_on_failed: コマンドの失敗時(return code != 0) にテストを error 扱いにする (default:False)
    :return: - **stdout** (*string*) - 実行したコマンドの標準出力
             - **stderr** (*string*) - 実行したコマンドの標準エラー
             - **returncode** (*int*) - 実行したコマンドの終了ステータス
    """
    before_curdir = path.abspath(os.curdir)

    if curdir:
      os.chdir(curdir)

    stdin_pipe = PIPE
    stdout_pipe = PIPE
    stderr_pipe = PIPE
    proc = Popen(cmd,
        stdin=stdin_pipe, stdout=stdout_pipe, stderr=stderr_pipe, shell=shell)
    (stdoutdata, stderrdata) = proc.communicate(stdin)

    stdoutdata = util.unicode_os_string(stdoutdata)
    stderrdata = util.unicode_os_string(stderrdata)

    if error_on_failed and proc.returncode != 0:
      raise Exception(stderrdata.strip() + ' (code=' + util.unicode(proc.returncode) + ')')

    self.output = {
        'stdout': stdoutdata,
        'stderr': stderrdata,
        'returncode': proc.returncode
    }

    os.chdir(before_curdir)
コード例 #10
0
ファイル: debugprinter.py プロジェクト: bigwheel/zaffy
  def smart_write(self, params):
    """ 与えられた文字列値を python の基本データ型のリテラルとして解釈した後に print する

    .. code-block:: yaml

       - サンプルシナリオ

       - action: debug.print
         v1: "1 + 2 + 3" #=> 6 と表示
         v2: "[1, 2] + [3, 4]" #=> [1, 2, 3, 4] と表示
    """
    dump = {}
    for key, value in params.items():
      if isinstance(value, util.basestring):
        try:
          # debug中で任意のコードが実行されないように、
          # ビルトイン関数を無効にしてリテラルと一部の式だけ解釈できるようにする
          dump[key] = eval(value, {'__builtins__':{}}, {})
        except Exception:
          dump[key] = util.unicode(value)
      else:
        dump[key] = value
    self.write(dump)
コード例 #11
0
ファイル: url.py プロジェクト: bigwheel/zaffy
def do_asurl(value):
  parsed = urlsplit(util.unicode(value))
  response = SplitResultWithQuery(parsed.scheme, parsed.netloc,
                                  parsed.path, parsed.query, parsed.fragment)
  return response
コード例 #12
0
ファイル: stdout.py プロジェクト: bigwheel/zaffy
 def write(self, data, option={}):
     data = util.unicode(data, errors="replace")
     # normalizing for output
     sys.stdout.write(util.normalize_write_string(data, default_out_encoding))
コード例 #13
0
ファイル: tap.py プロジェクト: bigwheel/zaffy
# -*- coding: utf-8 -*-
import util
import pprint
from . import YamlDumper


_u = lambda x: util.unicode(x, errors='replace')


def _i(prefix, output_string, postfix="\n"):
  """ 行先頭に "ok" 等の文字が出力されないようにフォーマットする
  """
  return "\n".join([prefix + line for line in output_string.rstrip().split("\n")]) + postfix


def _dump(obj):
  return _u(YamlDumper.dump(obj))


class Tap(object):
  def __init__(self, writer):
    self.writer = writer
    self.test_count = 0
    self.succeeded = 0
    self.failed = 0
    self.errored = 0
    self.not_ok_list = []
    self.current = None

  def finished(self):
    return self.succeeded + self.failed + self.errored
コード例 #14
0
ファイル: template.py プロジェクト: bigwheel/zaffy
 def __init__(self, original, template):
   super(TemplateFormatException, self).__init__(util.unicode(original))
   self.template = template
コード例 #15
0
ファイル: _json.py プロジェクト: bigwheel/zaffy
def do_asjson(value):
  return json.loads(util.unicode(value))
コード例 #16
0
ファイル: separate.py プロジェクト: bigwheel/zaffy
def do_ascsv(value, delim=',', quote='"'):
  reader = csv.reader(io.StringIO(util.unicode(value)), delimiter=delim, quotechar=quote)
  return list(reader)
コード例 #17
0
ファイル: url.py プロジェクト: bigwheel/zaffy
def do_asurlquerylist(value):
  return parse_qsl(util.unicode(value), True)
コード例 #18
0
ファイル: debugprinter.py プロジェクト: bigwheel/zaffy
 def write(self, params):
   params['__file__'] = self.scenario.setting.filename
   params['__index__'] = self.scenario.action_index
   params['__time__'] = util.unicode(datetime.datetime.now())
   self.formatter.debug(params)