Python os.EX_SOFTWARE Examples

The following are 25 code examples of os.EX_SOFTWARE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: test.py    From aegea with Apache License 2.0 6 votes vote down vote up
def test_dry_run_commands(self):
        unauthorized_ok = [dict(return_codes=[os.EX_OK]),
                           dict(return_codes=[1, os.EX_SOFTWARE], stderr="UnauthorizedOperation")]
        self.call("aegea launch unittest --dry-run --storage /x=512 /y=1024 --ubuntu-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --no-verify-ssh-key-pem-file --ubuntu-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --spot --no-verify-ssh-key-pem-file --amazon-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --duration-hours 1 --no-verify-ssh-key-pem-file --amazon-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call(("aegea launch unittest --duration 0.5 --min-mem 6 --cores 2 --dry-run --no-verify --client-token t "
                   "--amazon-linux-ami"),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea build-ami i --dry-run --no-verify-ssh-key-pem-file",
                  shell=True, expect=unauthorized_ok)

        self.call("aegea batch submit --command pwd --dry-run", shell=True)
        self.call("echo pwd > run.sh && aegea batch submit --execute run.sh --dry-run", shell=True)
        self.call("aegea batch submit --wdl '{}' --dry-run".format(__file__.replace(".py", ".wdl")), shell=True)

        self.call("aegea ecs run --command pwd --dry-run", shell=True) 
Example #2
Source File: test_taskpool.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def test_task_failed_exit(mocked_plugin, tpool, configure_model, freeze_time):
    tsk = create_task()

    polled = {"a": False}

    def side_effect(*args, **kwargs):
        if polled["a"]:
            return False
        polled["a"] = True
        return True

    mocked_plugin.alive.side_effect = side_effect
    mocked_plugin.returncode = os.EX_SOFTWARE

    tpool.submit(tsk)
    time.sleep(2)
    tsk.refresh()
    assert tsk.executor_host == platform.node()
    assert tsk.executor_pid == 100
    assert tsk.time_failed == int(freeze_time.return_value)
    assert not tsk.time_cancelled
    assert not tsk.time_completed
    assert not tpool.global_stop_event.is_set()
    assert tsk._id not in tpool.data 
Example #3
Source File: decorators.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def catch_errors(func):
    """Decorator which catches all errors and tries to print them."""

    @six.wraps(func)
    @click.pass_context
    def decorator(ctx, *args, **kwargs):
        try:
            return func(*args, **kwargs)
        except exceptions.DecapodAPIError as exc:
            utils.format_output_json(ctx, exc.json, True)
        except exceptions.DecapodError as exc:
            click.echo(six.text_type(exc), err=True)
        finally:
            ctx.close()

        ctx.exit(os.EX_SOFTWARE)

    return decorator 
Example #4
Source File: report.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    try:
        in_filename = argv[0]
    except IndexError:
        print(globals()['__doc__'], file=sys.stderr)
        return os.EX_USAGE

    try:
        report_segy(in_filename)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #5
Source File: common.py    From concierge with MIT License 6 votes vote down vote up
def main(app_class):
    def main_func():
        parser = concierge.endpoints.cli.create_parser()
        parser = app_class.specify_parser(parser)
        options = parser.parse_args()
        app = app_class(options)

        LOG.debug("Options: %s", options)

        try:
            return app.do()
        except KeyboardInterrupt:
            pass
        except Exception as exc:
            LOG.exception("Failed with error %s", exc)
            return os.EX_SOFTWARE

    return main_func 
Example #6
Source File: custom_header.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    try:
        in_filename = argv[0]
    except IndexError:
        print(globals()['__doc__'], file=sys.stderr)
        return os.EX_USAGE

    try:
        report_segy(in_filename)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #7
Source File: scale_source_coords.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    try:
        scale_factor = float(argv[0])
        in_filename = argv[1]
        out_filename = argv[2]
    except (ValueError, IndexError):
        print(globals()['__doc__'], file=sys.stderr)
        return os.EX_USAGE

    try:
        transform(scale_factor, in_filename, out_filename)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #8
Source File: test_script.py    From ldap2pg with PostgreSQL License 6 votes vote down vote up
def test_pdb(mocker):
    mocker.patch('ldap2pg.script.dictConfig', autospec=True)
    mocker.patch('ldap2pg.script.os.environ', {'DEBUG': '1'})
    isatty = mocker.patch('ldap2pg.script.sys.stdout.isatty')
    isatty.return_value = True
    w = mocker.patch('ldap2pg.script.wrapped_main')
    w.side_effect = Exception()
    pm = mocker.patch('ldap2pg.script.pdb.post_mortem')

    from ldap2pg.script import main

    with pytest.raises(SystemExit) as ei:
        main()

    assert pm.called is True
    assert os.EX_SOFTWARE == ei.value.code 
Example #9
Source File: loadsave.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    try:
        in_filename = argv[0]
        out_filename = argv[1]
    except IndexError:
        print(globals()['__doc__'], file=sys.stderr)
        return os.EX_USAGE

    try:
        load_save(in_filename, out_filename)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #10
Source File: scale_samples.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    try:
        scale_factor = float(argv[0])
        in_filename = argv[1]
        out_filename = argv[2]
    except (ValueError, IndexError):
        print(globals()['__doc__'], file=sys.stderr)
        return os.EX_USAGE

    try:
        transform(scale_factor, in_filename, out_filename)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #11
Source File: timed_reader.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    try:
        in_filename = argv[0]
    except IndexError:
        print(globals()['__doc__'], file=sys.stderr)
        return os.EX_USAGE

    try:
        read_traces(in_filename)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #12
Source File: script.py    From ldap2pg with PostgreSQL License 6 votes vote down vote up
def main():
    config = Configuration()
    debug = False

    try:
        debug = config.bootstrap(environ=os.environ)
        if debug:
            logger.debug("Debug mode enabled.")
        exit(wrapped_main(config))
    except pdb.bdb.BdbQuit:
        logger.info("Graceful exit from debugger.")
    except UserError as e:
        logger.critical("%s", e)
        exit(e.exit_code)
    except Exception:
        logger.exception('Unhandled error:')
        if debug and sys.stdout.isatty():
            logger.debug("Dropping in debugger.")
            pdb.post_mortem(sys.exc_info()[2])
        else:
            logger.error(
                "Please file an issue at "
                "https://github.com/dalibo/ldap2pg/issues with full log.",
            )
    exit(os.EX_SOFTWARE) 
Example #13
Source File: ceph_verify.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def catch_errors(func):
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as exc:
            LOG.error("Version verification has been failed: %s", exc)
            return os.EX_SOFTWARE

        return os.EX_OK

    return decorator 
Example #14
Source File: __init__.py    From aegea with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    parsed_args = parser.parse_args(args=args)
    logger.setLevel(parsed_args.log_level)
    has_attrs = (getattr(parsed_args, "sort_by", None) and getattr(parsed_args, "columns", None))
    if has_attrs and parsed_args.sort_by not in parsed_args.columns:
        parsed_args.columns.append(parsed_args.sort_by)
    try:
        result = parsed_args.entry_point(parsed_args)
    except Exception as e:
        if isinstance(e, NoRegionError):
            msg = "The AWS CLI is not configured."
            msg += " Please configure it using instructions at"
            msg += " http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html"
            exit(msg)
        elif logger.level < logging.ERROR:
            raise
        else:
            err_msg = traceback.format_exc()
            try:
                err_log_filename = os.path.join(config.user_config_dir, "error.log")
                with open(err_log_filename, "ab") as fh:
                    print(datetime.datetime.now().isoformat(), file=fh)
                    print(err_msg, file=fh)
                exit("{}: {}. See {} for error details.".format(e.__class__.__name__, e, err_log_filename))
            except Exception:
                print(err_msg, file=sys.stderr)
                exit(os.EX_SOFTWARE)
    if isinstance(result, SystemExit):
        raise result
    elif result is not None:
        if isinstance(result, dict) and "ResponseMetadata" in result:
            del result["ResponseMetadata"]
        print(json.dumps(result, indent=2, default=str)) 
Example #15
Source File: test_script.py    From ldap2pg with PostgreSQL License 5 votes vote down vote up
def test_unhandled_error(mocker):
    mocker.patch('ldap2pg.script.dictConfig', autospec=True)
    w = mocker.patch('ldap2pg.script.wrapped_main')

    from ldap2pg.script import main

    w.side_effect = Exception()

    with pytest.raises(SystemExit) as ei:
        main()

    assert os.EX_SOFTWARE == ei.value.code 
Example #16
Source File: test_script.py    From ldap2pg with PostgreSQL License 5 votes vote down vote up
def test_bdb_quit(mocker):
    mocker.patch('ldap2pg.script.dictConfig', autospec=True)
    w = mocker.patch('ldap2pg.script.wrapped_main')

    from ldap2pg.script import main, pdb

    w.side_effect = pdb.bdb.BdbQuit()

    with pytest.raises(SystemExit) as ei:
        main()

    assert os.EX_SOFTWARE == ei.value.code 
Example #17
Source File: extract_trace_header_field.py    From segpy with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("segy_file", metavar="segy-file",
                        help="Path to an existing SEG Y file of 3D seismic data")

    parser.add_argument("npy_file", metavar="npy-file",
                        help="Path to the Numpy array file to be created for the header")

    parser.add_argument("field_name", metavar="field-name", type=str,
                        help="Name of the trace header field to be extracted", )

    parser.add_argument("--null",  type=nullable_int, default="",
                        help="Header value to use for missing or short traces.")

    if argv is None:
        argv = sys.argv[1:]

    args = parser.parse_args(argv)

    try:
        extract_header_field(
            segy_filename=args.segy_file,
            out_filename=args.npy_file,
            field_name=args.field_name,
            null=args.null)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #18
Source File: extract_inline.py    From segpy with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("segy_file", metavar="segy-file",
                        help="Path to an existing SEG Y file of 3D seismic data")

    parser.add_argument("npy_file", metavar="npy-file",
                        help="Path to the Numpy array file to be created for the timeslice")

    parser.add_argument("inline_number", metavar="inline-number", type=int,
                        help="Zero based index of the inline to be extracted", )

    parser.add_argument("--null",  type=nullable_float, default="",
                        help="Sample value to use for missing or short traces.")

    if argv is None:
        argv = sys.argv[1:]

    args = parser.parse_args(argv)

    try:
        inline_array = extract_inline(
            segy_filename=args.segy_file,
            inline_number=args.inline_number,
            null=args.null)
        inline_array.tofile(args.npy_file)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #19
Source File: convert_sample_type.py    From segpy with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    try:
        data_sample_format = argv[0]
        in_filename = argv[1]
        out_filename = argv[2]
    except (ValueError, IndexError):
        print(globals()['__doc__'], file=sys.stderr)
        return os.EX_USAGE

    if data_sample_format not in SEG_Y_TYPE_DESCRIPTION:
        print("Accepted data sample formats:")
        for name, description in SEG_Y_TYPE_DESCRIPTION.items():
            print("{} : {}".format(name, description))
        return os.EX_USAGE

    if out_filename == in_filename:
        print("Output filename {} is the same as input filename".format(out_filename, in_filename))
        return os.EX_USAGE

    try:
        transform(data_sample_format, in_filename, out_filename)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #20
Source File: timeslice.py    From segpy with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("segy_file", metavar="segy-file",
                        help="Path to an existing SEG Y file of 3D seismic data")

    parser.add_argument("npy_file", metavar="npy-file",
                        help="Path to the Numpy array file to be created for the timeslice")

    parser.add_argument("slice_index", metavar="slice-index", type=int,
                        help="Zero based index of the time slice to be extracted", )

    parser.add_argument("--dtype", type=nullable_dtype, default="",
                        help="Numpy data type. If not provided a dtype compatible with the SEG Y data will be used.")

    parser.add_argument("--null",  type=float, default=0.0,
                        help="Sample value to use for missing or short traces.")

    if argv is None:
        argv = sys.argv[1:]

    args = parser.parse_args(argv)

    try:
        extract_timeslice(args.segy_file,
                          args.npy_file,
                          args.slice_index,
                          args.dtype,
                          args.null)
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e, file=sys.stderr)
        return os.EX_NOINPUT
    except PermissionError as e:
        print(e, file=sys.stderr)
        return os.EX_NOPERM
    except Exception as e:
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
        return os.EX_SOFTWARE
    return os.EX_OK 
Example #21
Source File: deploy_impl.py    From loaner with Apache License 2.0 5 votes vote down vote up
def _ManifestCheck(self):
    """Check the manifest.json file for required key/value pairs.

    Raises:
      ManifestError: when there is an issue with the manifest.json file.
    """
    logging.debug('Checking the manifest file...')
    with open(self.manifest_file, 'r') as manifest_data:
      try:
        data = json.load(manifest_data)
      # Catch syntax errors.
      except ValueError:
        sys.stderr.write(
            "The there is a syntax error in the Chrome App's"
            "manifest.json file, located at: {}\n".format(self.manifest_file))
        raise ManifestError(os.EX_SOFTWARE)
      # Set the new version.
      current_version = data['version']
      data['version'] = input(
          'The current Chrome App version is {}, '
          'please enter the new version: '.format(current_version))
      # Check for the Chrome App Key.
      if not data['key']:
        sys.stderr.write(
            "The manifest key is missing, please place it in the Chrome App's "
            "manifest.json file, located at: {}\n".format(self.manifest_file))
        raise ManifestError(os.EX_SOFTWARE)
      # Check for the OAuth2 Client ID.
      if not data['oauth2']['client_id']:
        sys.stderr.write(
            "The OAuth2 Client ID is missing for the Chrome App, please place "
            "it in the Chrome App's manifest.json, "
            "file located at: {}\n".format(
                self.manifest_file))
        raise ManifestError(os.EX_SOFTWARE)

    # Write new version to manifest.
    with open(self.manifest_file, 'w+') as manifest_data:
      json.dump(
          data, manifest_data, sort_keys=True, indent=2, separators=(',', ': ')) 
Example #22
Source File: test.py    From aegea with Apache License 2.0 5 votes vote down vote up
def test_secrets(self):
        unauthorized_ok = [dict(return_codes=[os.EX_OK]),
                           dict(return_codes=[1, os.EX_SOFTWARE], stderr="(AccessDenied|NoSuchKey)")]
        secret_name = "test_secret_{}".format(int(time.time()))
        self.call("{s}=test aegea secrets put {s} --iam-role aegea.launch".format(s=secret_name),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea secrets put {s} --generate-ssh-key --iam-role aegea.launch".format(s=secret_name),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea secrets ls", shell=True, expect=unauthorized_ok)
        self.call("aegea secrets ls --json", shell=True, expect=unauthorized_ok)
        self.call("aegea secrets get {s} --iam-role aegea.launch".format(s=secret_name), shell=True,
                  expect=unauthorized_ok)
        self.call("aegea secrets delete {s} --iam-role aegea.launch".format(s=secret_name), shell=True,
                  expect=unauthorized_ok) 
Example #23
Source File: __main__.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def main():
	parser = argparse.ArgumentParser(prog='KingPhisherServer', description='King Phisher Server', conflict_handler='resolve')
	utilities.argp_add_args(parser)
	startup.argp_add_server(parser)
	arguments = parser.parse_args()

	# basic runtime checks
	if sys.version_info < (3, 4):
		color.print_error('the python version is too old (minimum required is 3.4)')
		return 0

	console_log_handler = utilities.configure_stream_logger(arguments.logger, arguments.loglvl)
	del parser

	# configure environment variables and load the config
	find.init_data_path('server')
	if not os.path.exists(arguments.config_file):
		color.print_error('invalid configuration file')
		color.print_error('the specified path does not exist')
		return os.EX_NOINPUT
	if not os.path.isfile(arguments.config_file):
		color.print_error('invalid configuration file')
		color.print_error('the specified path is not a file')
		return os.EX_NOINPUT
	if not os.access(arguments.config_file, os.R_OK):
		color.print_error('invalid configuration file')
		color.print_error('the specified path can not be read')
		return os.EX_NOPERM
	config = configuration.ex_load_config(arguments.config_file)
	if arguments.verify_config:
		color.print_good('configuration verification passed')
		color.print_good('all required settings are present')
		return os.EX_OK
	if config.has_option('server.data_path'):
		find.data_path_append(config.get('server.data_path'))

	if os.getuid():
		color.print_error('the server must be started as root, configure the')
		color.print_error('\'server.setuid_username\' option in the config file to drop privileges')
		return os.EX_NOPERM

	# setup logging based on the configuration
	if config.has_section('logging'):
		log_file = _ex_config_logging(arguments, config, console_log_handler)
	logger.debug("king phisher version: {0} python version: {1}.{2}.{3}".format(version.version, sys.version_info[0], sys.version_info[1], sys.version_info[2]))

	# initialize the plugin manager
	try:
		plugin_manager = plugins.ServerPluginManager(config)
	except errors.KingPhisherError as error:
		if isinstance(error, errors.KingPhisherPluginError):
			color.print_error("plugin error: {0} ({1})".format(error.plugin_name, error.message))
		else:
			color.print_error(error.message)
		return os.EX_SOFTWARE

	status_code = build_and_run(arguments, config, plugin_manager, log_file)
	plugin_manager.shutdown()
	logging.shutdown()
	return status_code 
Example #24
Source File: linky.py    From domoticz_linky with GNU General Public License v3.0 4 votes vote down vote up
def _get_data(session, resource_id, start_date=None, end_date=None):
    req_part = 'lincspartdisplaycdc_WAR_lincspartcdcportlet'

    # We send the session token so that the server knows who we are
    payload = {
        '_' + req_part + '_dateDebut': start_date,
        '_' + req_part + '_dateFin': end_date
    }

    params = {
        'p_p_id': req_part,
        'p_p_lifecycle': 2,
        'p_p_state': 'normal',
        'p_p_mode': 'view',
        'p_p_resource_id': resource_id,
        'p_p_cacheability': 'cacheLevelPage',
        'p_p_col_id': 'column-1',
        'p_p_col_count': 2
    }

    req = session.post(API_BASE_URI + API_ENDPOINT_DATA,
                       allow_redirects=False, data=payload, params=params)

    if 300 <= req.status_code < 400:
        # So... apparently, we may need to do that once again if we hit a 302
        # ¯\_(ツ)_/¯
        req = session.post(API_BASE_URI + API_ENDPOINT_DATA,
                           allow_redirects=False, data=payload, params=params)

    if req.status_code == 200 and req.text is not None:
        if "Conditions d'utilisation" in req.text:
            raise LinkyLoginException("You need to accept the latest Terms of Use. Please manually log into the website, then come back.")
        if "Une erreur technique" in req.text:
            raise LinkyLoginException("A technical error has occurred on website. Data unavailable.")

    try:
        res = json.loads(req.text)
    except:
        logging.info("Unable to log in")
        sys.exit(os.EX_SOFTWARE)
    # logging.info(resource_id+" ")
    # logging.info(res)
    if res['etat'] and res['etat']['valeur'] == 'erreur':
        raise LinkyServiceException(html.unescape(res['etat']))

    return res 
Example #25
Source File: test.py    From aegea with Apache License 2.0 4 votes vote down vote up
def test_basic_aegea_commands(self):
        self.call(["aegea"], expect=[dict(return_codes=[1])])
        self.call(["aegea", "--help"])
        self.call(["aegea", "--version"])
        self.call(["aegea", "pricing"])
        self.call(["aegea", "pricing", "AmazonEC2"])
        self.call(["aegea", "pricing", "AmazonRDS"])
        self.call(["aegea", "ls", "-w9"])
        for ssh_cmd in "ssh", "scp":
            self.call(["aegea", ssh_cmd, "nonexistent_instance:"],
                      expect=[dict(return_codes=[1, os.EX_SOFTWARE], stderr="AegeaException: Could not resolve")])
        instance_id = json.loads(self.call(["aegea", "ls", "--json"]).stdout)[0]["id"]
        for subcommand in aegea.parser._actions[-1].choices:
            expect = [dict(return_codes=[os.EX_OK]),
                      dict(return_codes=[1, os.EX_SOFTWARE],
                           stderr="(UnauthorizedOperation|AccessDenied|DryRunOperation)")]
            args = []
            if subcommand in ("ssh", "scp", "run", "put-alarm", "batch", "rm"):
                args += ["--help"]
            elif subcommand == "top" and sys.version_info < (3, 5):
                continue  # concurrent.futures.ThreadPoolExecutor thread count autotune introduced in 3.5
            elif "_" in subcommand:
                continue
            elif subcommand == "build-docker-image":
                args += ["--dry-run", "docker-example"]
            elif subcommand == "console":
                args += [instance_id]
            elif subcommand == "iam":
                args += ["users"]
            elif subcommand in ("start", "stop", "reboot", "terminate", "rename"):
                args += [instance_id, instance_id, "--dry-run"]
            elif subcommand in ("grep", "filter"):
                args += ["--help"] if USING_PYTHON2 else ["error", "syslog", "--start-time=-2h", "--end-time=-5m"]
                expect.append(dict(return_codes=[os.EX_DATAERR]))
            elif subcommand == "launch":
                args += ["--no-verify-ssh-key-pem-file", "--dry-run", "test", "--ubuntu-linux-ami"]
            elif subcommand == "build-ami":
                args += ["--no-verify-ssh-key-pem-file", "--dry-run", "test"]
            elif subcommand == "s3":
                args += ["buckets"]
            elif subcommand in ("secrets", "rds", "elb", "flow-logs", "deploy", "zones", "ebs", "efs",
                                "ecr", "lambda", "configure", "sfn"):
                args += ["ls"]
            elif subcommand == "pricing":
                args += ["AmazonS3", "--json"]
            elif subcommand == "billing":
                continue  # FIXME
                args += ["ls", "--min-cost", "0.1"]
                if "AWS_BILLING_REPORTS_BUCKET" in os.environ:
                    args += ["--billing-reports-bucket", os.environ["AWS_BILLING_REPORTS_BUCKET"]]
            elif subcommand == "ls":
                args += ["--filter", "state=running"]
            elif subcommand == "tag":
                args += [instance_id, "test=test test2=test"]
            elif subcommand == "untag":
                args += [instance_id, "test test2"]
            elif subcommand == "ecs":
                args += ["clusters"]
            self.call(["aegea", subcommand] + args, expect=expect)