Exemplo n.º 1
0
def test_writeread(tmpdir, config):
    config.loadFromDict({
        'endpoint': 'api.nsone.net',
        'default_key': 'test1',
        'keys': {
            'test1': {
                'key': 'key-1',
                'desc': 'test key number 1',
                'writeLock': True
            }
        }
    })

    # Write config to temp.
    tmp_cfg_path = str(tmpdir.join('test_writeread.json'))
    config.write(tmp_cfg_path)

    # Read new but identical config instance.
    cfg_read = Config(tmp_cfg_path)
    assert cfg_read is not config
    assert cfg_read.getEndpoint() == config.getEndpoint()
    assert cfg_read.getCurrentKeyID() == config.getCurrentKeyID()
    assert cfg_read.isKeyWriteLocked() == config.isKeyWriteLocked()
Exemplo n.º 2
0
def test_writeread(tmpdir, config):
    config.loadFromDict({
        'endpoint': 'api.nsone.net',
        'default_key': 'test1',
        'keys': {
            'test1': {
                'key': 'key-1',
                'desc': 'test key number 1',
                'writeLock': True
            }
        }
    })

    # Write config to temp.
    tmp_cfg_path = str(tmpdir.join('test_writeread.json'))
    config.write(tmp_cfg_path)

    # Read new but identical config instance.
    cfg_read = Config(tmp_cfg_path)
    assert cfg_read is not config
    assert cfg_read.getEndpoint() == config.getEndpoint()
    assert cfg_read.getCurrentKeyID() == config.getCurrentKeyID()
    assert cfg_read.isKeyWriteLocked() == config.isKeyWriteLocked()
Exemplo n.º 3
0
Arquivo: cli.py Projeto: ns1/ns1-cli
    def load_rest_client(self):
        """Loads ns1 rest client config"""
        opts = self.rest_cfg_opts

        # Create default config without any key
        cfg = Config()
        cfg.createFromAPIKey('')

        if opts.get('path', None):
            cfg.loadFromFile(opts['path'])
        elif opts.get('api_key'):
            cfg.createFromAPIKey(opts['api_key'])
        else:
            path = os.path.join(self.home_dir, self.DEFAULT_CONFIG_FILE)
            if os.path.exists(path):
                cfg.loadFromFile(path)

        if opts.get('api_key_id'):
            cfg.useKeyId(opts['api_key_id'])

        if opts.get('endpoint'):
            cfg['endpoint'] = opts['endpoint']

        if opts.get('transport'):
            cfg['transport'] = opts['transport']

        if opts.get('ignore_ssl'):
            cfg['ignore-ssl-errors'] = opts['ignore_ssl']

        if cfg['ignore-ssl-errors']:
            import requests
            from requests.packages.urllib3.exceptions import InsecureRequestWarning
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

        # Store the cli cfg dict as an attr of the rest config instance.
        for k, v in self.cfg.items():
            cfg['cli'][k] = v

        self.rest = NSONE(config=cfg)
Exemplo n.º 4
0
def main():
    args = docopt(__doc__, version=BANNER, options_first=True)

    verbosity = args.get('-v', 0)
    if verbosity > 1:
        logging.basicConfig(level=logging.DEBUG)
    elif verbosity > 0:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.CRITICAL)
    # tweak requests logging
    if verbosity < 2:
        requests_log = logging.getLogger("requests")
        requests_log.setLevel(logging.WARNING)

    # if api key given, use a custom config
    config = None
    if args['--key']:
        config = Config()
        # this will save a .nsone with this key if one doesn't already exist
        config.createFromAPIKey(args['--key'], maybeWriteDefault=True)
        config['verbosity'] = verbosity

    try:
        nsone = NSONE(config=config)
    except ConfigException as e:
        print(e.message)
        sys.exit(1)
    except IOError as e:
        print('No config file was found. Either specify an API key (with -k) '
              'on the command line, or create %s' % Config.DEFAULT_CONFIG_FILE)
        sys.exit(1)

    # do config overrides in nsone based on cmd args
    if args['--format']:
        nsone.config['cli']['output_format'] = args['--format']

    # do defaults
    if 'output_format' not in nsone.config.get('cli', {}):
        nsone.config['cli']['output_format'] = 'text'

    if args['--endpoint']:
        nsone.config['endpoint'] = args['--endpoint']

    if args['--ignore-ssl-errors']:
        nsone.config['ignore-ssl-errors'] = args['--ignore-ssl-errors']
        if verbosity < 2:
            logging.captureWarnings(True)

    if args['--transport']:
        nsone.config['transport'] = args['--transport']

    BaseCommand.nsone = nsone

    cmd = args['<command>']

    if not cmd:
        info = "\nType 'help' for help\n\nCurrent Key: %s\nEndpoint: %s" % \
               (nsone.config.getCurrentKeyID(), nsone.config.getEndpoint())
        repl = NS1Repl(cmdListDoc, cmdList)
        repl.interact(BANNER + info)
        sys.exit(0)
    cmdArgs = args['<args>']
    subArgv = [cmd] + cmdArgs

    if cmd in cmdList.keys():
        svc = cmdList[cmd]
        try:
            subArgs = docopt(svc.__doc__, argv=subArgv, options_first=True)
        except DocoptExit as e:
            if cmd == 'help':
                print(__doc__)
            else:
                print(e.usage)
            sys.exit(1)
        try:
            svc.run(subArgs)
        except ResourceException as e:
            print('REST API error: %s' % e.message)
        except CommandException as e:
            print(e.message)
            sys.exit(1)
    else:
        exit("%r is not a command. See 'ns1 help'." % cmd)
Exemplo n.º 5
0
    def load_rest_client(self):
        """Loads ns1 rest client config"""
        opts = self.rest_cfg_opts

        # Create default config without any key
        cfg = Config()
        cfg.createFromAPIKey('')

        if opts.get('path', None):
            cfg.loadFromFile(opts['path'])
        elif opts.get('api_key'):
            cfg.createFromAPIKey(opts['api_key'])
        else:
            path = os.path.join(self.home_dir, self.DEFAULT_CONFIG_FILE)
            if os.path.exists(path):
                cfg.loadFromFile(path)

        if opts.get('api_key_id'):
            cfg.useKeyId(opts['api_key_id'])

        if opts.get('endpoint'):
            cfg['endpoint'] = opts['endpoint']

        if opts.get('transport'):
            cfg['transport'] = opts['transport']

        if opts.get('ignore_ssl'):
            cfg['ignore-ssl-errors'] = opts['ignore_ssl']

        if cfg['ignore-ssl-errors']:
            import requests
            from requests.packages.urllib3.exceptions import InsecureRequestWarning
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

        # Store the cli cfg dict as an attr of the rest config instance.
        for k, v in self.cfg.items():
            cfg['cli'][k] = v

        self.rest = NSONE(config=cfg)
Exemplo n.º 6
0
 def test_writeread(self):
     cfg = self._load_from_str()
     cfg.write(self.TEST_PATH)
     cfg2 = Config(self.TEST_PATH)
     self.assertEqual(cfg2['default_key'], 'test1')
Exemplo n.º 7
0
 def test_need_path(self):
     cfg = Config()
     self.assertRaises(ConfigException, cfg.write)
Exemplo n.º 8
0
 def _load_from_str(self):
     json_str = json.dumps(self.TEST_CONFIG_1)
     cfg = Config()
     cfg.loadFromString(json_str)
     return cfg