Best Python code snippet using autotest_python
__init__.py
Source:__init__.py  
1# coding=utf-82# --------------------------------------------------------------------------3# Copyright (c) Microsoft Corporation. All rights reserved.4# Licensed under the MIT License. See License.txt in the project root for5# license information.6#7# Code generated by Microsoft (R) AutoRest Code Generator.8# Changes may cause incorrect behavior and will be lost if the code is9# regenerated.10# --------------------------------------------------------------------------11from .pool_usage_metrics import PoolUsageMetrics12from .image_reference import ImageReference13from .node_agent_sku import NodeAgentSku14from .authentication_token_settings import AuthenticationTokenSettings15from .usage_statistics import UsageStatistics16from .resource_statistics import ResourceStatistics17from .pool_statistics import PoolStatistics18from .job_statistics import JobStatistics19from .name_value_pair import NameValuePair20from .delete_certificate_error import DeleteCertificateError21from .certificate import Certificate22from .application_package_reference import ApplicationPackageReference23from .application_summary import ApplicationSummary24from .certificate_add_parameter import CertificateAddParameter25from .file_properties import FileProperties26from .node_file import NodeFile27from .schedule import Schedule28from .job_constraints import JobConstraints29from .resource_file import ResourceFile30from .environment_setting import EnvironmentSetting31from .exit_options import ExitOptions32from .exit_code_mapping import ExitCodeMapping33from .exit_code_range_mapping import ExitCodeRangeMapping34from .exit_conditions import ExitConditions35from .auto_user_specification import AutoUserSpecification36from .user_identity import UserIdentity37from .linux_user_configuration import LinuxUserConfiguration38from .user_account import UserAccount39from .task_constraints import TaskConstraints40from .output_file_blob_container_destination import OutputFileBlobContainerDestination41from .output_file_destination import OutputFileDestination42from .output_file_upload_options import OutputFileUploadOptions43from .output_file import OutputFile44from .job_manager_task import JobManagerTask45from .job_preparation_task import JobPreparationTask46from .job_release_task import JobReleaseTask47from .task_scheduling_policy import TaskSchedulingPolicy48from .start_task import StartTask49from .certificate_reference import CertificateReference50from .metadata_item import MetadataItem51from .cloud_service_configuration import CloudServiceConfiguration52from .os_disk import OSDisk53from .windows_configuration import WindowsConfiguration54from .virtual_machine_configuration import VirtualMachineConfiguration55from .network_security_group_rule import NetworkSecurityGroupRule56from .inbound_nat_pool import InboundNATPool57from .pool_endpoint_configuration import PoolEndpointConfiguration58from .network_configuration import NetworkConfiguration59from .pool_specification import PoolSpecification60from .auto_pool_specification import AutoPoolSpecification61from .pool_information import PoolInformation62from .job_specification import JobSpecification63from .recent_job import RecentJob64from .job_schedule_execution_information import JobScheduleExecutionInformation65from .job_schedule_statistics import JobScheduleStatistics66from .cloud_job_schedule import CloudJobSchedule67from .job_schedule_add_parameter import JobScheduleAddParameter68from .job_scheduling_error import JobSchedulingError69from .job_execution_information import JobExecutionInformation70from .cloud_job import CloudJob71from .job_add_parameter import JobAddParameter72from .task_failure_information import TaskFailureInformation73from .job_preparation_task_execution_information import JobPreparationTaskExecutionInformation74from .job_release_task_execution_information import JobReleaseTaskExecutionInformation75from .job_preparation_and_release_task_execution_information import JobPreparationAndReleaseTaskExecutionInformation76from .task_counts import TaskCounts77from .auto_scale_run_error import AutoScaleRunError78from .auto_scale_run import AutoScaleRun79from .resize_error import ResizeError80from .cloud_pool import CloudPool81from .pool_add_parameter import PoolAddParameter82from .affinity_information import AffinityInformation83from .task_execution_information import TaskExecutionInformation84from .compute_node_information import ComputeNodeInformation85from .multi_instance_settings import MultiInstanceSettings86from .task_statistics import TaskStatistics87from .task_id_range import TaskIdRange88from .task_dependencies import TaskDependencies89from .cloud_task import CloudTask90from .task_add_parameter import TaskAddParameter91from .task_add_collection_parameter import TaskAddCollectionParameter92from .error_message import ErrorMessage93from .batch_error_detail import BatchErrorDetail94from .batch_error import BatchError, BatchErrorException95from .task_add_result import TaskAddResult96from .task_add_collection_result import TaskAddCollectionResult97from .subtask_information import SubtaskInformation98from .cloud_task_list_subtasks_result import CloudTaskListSubtasksResult99from .task_information import TaskInformation100from .start_task_information import StartTaskInformation101from .compute_node_error import ComputeNodeError102from .inbound_endpoint import InboundEndpoint103from .compute_node_endpoint_configuration import ComputeNodeEndpointConfiguration104from .compute_node import ComputeNode105from .compute_node_user import ComputeNodeUser106from .compute_node_get_remote_login_settings_result import ComputeNodeGetRemoteLoginSettingsResult107from .job_schedule_patch_parameter import JobSchedulePatchParameter108from .job_schedule_update_parameter import JobScheduleUpdateParameter109from .job_disable_parameter import JobDisableParameter110from .job_terminate_parameter import JobTerminateParameter111from .job_patch_parameter import JobPatchParameter112from .job_update_parameter import JobUpdateParameter113from .pool_enable_auto_scale_parameter import PoolEnableAutoScaleParameter114from .pool_evaluate_auto_scale_parameter import PoolEvaluateAutoScaleParameter115from .pool_resize_parameter import PoolResizeParameter116from .pool_update_properties_parameter import PoolUpdatePropertiesParameter117from .pool_upgrade_os_parameter import PoolUpgradeOSParameter118from .pool_patch_parameter import PoolPatchParameter119from .task_update_parameter import TaskUpdateParameter120from .node_update_user_parameter import NodeUpdateUserParameter121from .node_reboot_parameter import NodeRebootParameter122from .node_reimage_parameter import NodeReimageParameter123from .node_disable_scheduling_parameter import NodeDisableSchedulingParameter124from .node_remove_parameter import NodeRemoveParameter125from .application_list_options import ApplicationListOptions126from .application_get_options import ApplicationGetOptions127from .pool_list_usage_metrics_options import PoolListUsageMetricsOptions128from .pool_get_all_lifetime_statistics_options import PoolGetAllLifetimeStatisticsOptions129from .pool_add_options import PoolAddOptions130from .pool_list_options import PoolListOptions131from .pool_delete_options import PoolDeleteOptions132from .pool_exists_options import PoolExistsOptions133from .pool_get_options import PoolGetOptions134from .pool_patch_options import PoolPatchOptions135from .pool_disable_auto_scale_options import PoolDisableAutoScaleOptions136from .pool_enable_auto_scale_options import PoolEnableAutoScaleOptions137from .pool_evaluate_auto_scale_options import PoolEvaluateAutoScaleOptions138from .pool_resize_options import PoolResizeOptions139from .pool_stop_resize_options import PoolStopResizeOptions140from .pool_update_properties_options import PoolUpdatePropertiesOptions141from .pool_upgrade_os_options import PoolUpgradeOsOptions142from .pool_remove_nodes_options import PoolRemoveNodesOptions143from .account_list_node_agent_skus_options import AccountListNodeAgentSkusOptions144from .job_get_all_lifetime_statistics_options import JobGetAllLifetimeStatisticsOptions145from .job_delete_options import JobDeleteOptions146from .job_get_options import JobGetOptions147from .job_patch_options import JobPatchOptions148from .job_update_options import JobUpdateOptions149from .job_disable_options import JobDisableOptions150from .job_enable_options import JobEnableOptions151from .job_terminate_options import JobTerminateOptions152from .job_add_options import JobAddOptions153from .job_list_options import JobListOptions154from .job_list_from_job_schedule_options import JobListFromJobScheduleOptions155from .job_list_preparation_and_release_task_status_options import JobListPreparationAndReleaseTaskStatusOptions156from .job_get_task_counts_options import JobGetTaskCountsOptions157from .certificate_add_options import CertificateAddOptions158from .certificate_list_options import CertificateListOptions159from .certificate_cancel_deletion_options import CertificateCancelDeletionOptions160from .certificate_delete_options import CertificateDeleteOptions161from .certificate_get_options import CertificateGetOptions162from .file_delete_from_task_options import FileDeleteFromTaskOptions163from .file_get_from_task_options import FileGetFromTaskOptions164from .file_get_properties_from_task_options import FileGetPropertiesFromTaskOptions165from .file_delete_from_compute_node_options import FileDeleteFromComputeNodeOptions166from .file_get_from_compute_node_options import FileGetFromComputeNodeOptions167from .file_get_properties_from_compute_node_options import FileGetPropertiesFromComputeNodeOptions168from .file_list_from_task_options import FileListFromTaskOptions169from .file_list_from_compute_node_options import FileListFromComputeNodeOptions170from .job_schedule_exists_options import JobScheduleExistsOptions171from .job_schedule_delete_options import JobScheduleDeleteOptions172from .job_schedule_get_options import JobScheduleGetOptions173from .job_schedule_patch_options import JobSchedulePatchOptions174from .job_schedule_update_options import JobScheduleUpdateOptions175from .job_schedule_disable_options import JobScheduleDisableOptions176from .job_schedule_enable_options import JobScheduleEnableOptions177from .job_schedule_terminate_options import JobScheduleTerminateOptions178from .job_schedule_add_options import JobScheduleAddOptions179from .job_schedule_list_options import JobScheduleListOptions180from .task_add_options import TaskAddOptions181from .task_list_options import TaskListOptions182from .task_add_collection_options import TaskAddCollectionOptions183from .task_delete_options import TaskDeleteOptions184from .task_get_options import TaskGetOptions185from .task_update_options import TaskUpdateOptions186from .task_list_subtasks_options import TaskListSubtasksOptions187from .task_terminate_options import TaskTerminateOptions188from .task_reactivate_options import TaskReactivateOptions189from .compute_node_add_user_options import ComputeNodeAddUserOptions190from .compute_node_delete_user_options import ComputeNodeDeleteUserOptions191from .compute_node_update_user_options import ComputeNodeUpdateUserOptions192from .compute_node_get_options import ComputeNodeGetOptions193from .compute_node_reboot_options import ComputeNodeRebootOptions194from .compute_node_reimage_options import ComputeNodeReimageOptions195from .compute_node_disable_scheduling_options import ComputeNodeDisableSchedulingOptions196from .compute_node_enable_scheduling_options import ComputeNodeEnableSchedulingOptions197from .compute_node_get_remote_login_settings_options import ComputeNodeGetRemoteLoginSettingsOptions198from .compute_node_get_remote_desktop_options import ComputeNodeGetRemoteDesktopOptions199from .compute_node_list_options import ComputeNodeListOptions200from .application_summary_paged import ApplicationSummaryPaged201from .pool_usage_metrics_paged import PoolUsageMetricsPaged202from .cloud_pool_paged import CloudPoolPaged203from .node_agent_sku_paged import NodeAgentSkuPaged204from .cloud_job_paged import CloudJobPaged205from .job_preparation_and_release_task_execution_information_paged import JobPreparationAndReleaseTaskExecutionInformationPaged206from .certificate_paged import CertificatePaged207from .node_file_paged import NodeFilePaged208from .cloud_job_schedule_paged import CloudJobSchedulePaged209from .cloud_task_paged import CloudTaskPaged210from .compute_node_paged import ComputeNodePaged211from .batch_service_client_enums import (212    OSType,213    AccessScope,214    CertificateState,215    CertificateFormat,216    JobAction,217    DependencyAction,218    AutoUserScope,219    ElevationLevel,220    OutputFileUploadCondition,221    ComputeNodeFillType,222    CertificateStoreLocation,223    CertificateVisibility,224    CachingType,225    InboundEndpointProtocol,226    NetworkSecurityGroupRuleAccess,227    PoolLifetimeOption,228    OnAllTasksComplete,229    OnTaskFailure,230    JobScheduleState,231    ErrorCategory,232    JobState,233    JobPreparationTaskState,234    TaskExecutionResult,235    JobReleaseTaskState,236    TaskCountValidationStatus,237    PoolState,238    AllocationState,239    TaskState,240    TaskAddStatus,241    SubtaskState,242    StartTaskState,243    ComputeNodeState,244    SchedulingState,245    DisableJobOption,246    ComputeNodeDeallocationOption,247    ComputeNodeRebootOption,248    ComputeNodeReimageOption,249    DisableComputeNodeSchedulingOption,250)251__all__ = [252    'PoolUsageMetrics',253    'ImageReference',254    'NodeAgentSku',255    'AuthenticationTokenSettings',256    'UsageStatistics',257    'ResourceStatistics',258    'PoolStatistics',259    'JobStatistics',260    'NameValuePair',261    'DeleteCertificateError',262    'Certificate',263    'ApplicationPackageReference',264    'ApplicationSummary',265    'CertificateAddParameter',266    'FileProperties',267    'NodeFile',268    'Schedule',269    'JobConstraints',270    'ResourceFile',271    'EnvironmentSetting',272    'ExitOptions',273    'ExitCodeMapping',274    'ExitCodeRangeMapping',275    'ExitConditions',276    'AutoUserSpecification',277    'UserIdentity',278    'LinuxUserConfiguration',279    'UserAccount',280    'TaskConstraints',281    'OutputFileBlobContainerDestination',282    'OutputFileDestination',283    'OutputFileUploadOptions',284    'OutputFile',285    'JobManagerTask',286    'JobPreparationTask',287    'JobReleaseTask',288    'TaskSchedulingPolicy',289    'StartTask',290    'CertificateReference',291    'MetadataItem',292    'CloudServiceConfiguration',293    'OSDisk',294    'WindowsConfiguration',295    'VirtualMachineConfiguration',296    'NetworkSecurityGroupRule',297    'InboundNATPool',298    'PoolEndpointConfiguration',299    'NetworkConfiguration',300    'PoolSpecification',301    'AutoPoolSpecification',302    'PoolInformation',303    'JobSpecification',304    'RecentJob',305    'JobScheduleExecutionInformation',306    'JobScheduleStatistics',307    'CloudJobSchedule',308    'JobScheduleAddParameter',309    'JobSchedulingError',310    'JobExecutionInformation',311    'CloudJob',312    'JobAddParameter',313    'TaskFailureInformation',314    'JobPreparationTaskExecutionInformation',315    'JobReleaseTaskExecutionInformation',316    'JobPreparationAndReleaseTaskExecutionInformation',317    'TaskCounts',318    'AutoScaleRunError',319    'AutoScaleRun',320    'ResizeError',321    'CloudPool',322    'PoolAddParameter',323    'AffinityInformation',324    'TaskExecutionInformation',325    'ComputeNodeInformation',326    'MultiInstanceSettings',327    'TaskStatistics',328    'TaskIdRange',329    'TaskDependencies',330    'CloudTask',331    'TaskAddParameter',332    'TaskAddCollectionParameter',333    'ErrorMessage',334    'BatchErrorDetail',335    'BatchError', 'BatchErrorException',336    'TaskAddResult',337    'TaskAddCollectionResult',338    'SubtaskInformation',339    'CloudTaskListSubtasksResult',340    'TaskInformation',341    'StartTaskInformation',342    'ComputeNodeError',343    'InboundEndpoint',344    'ComputeNodeEndpointConfiguration',345    'ComputeNode',346    'ComputeNodeUser',347    'ComputeNodeGetRemoteLoginSettingsResult',348    'JobSchedulePatchParameter',349    'JobScheduleUpdateParameter',350    'JobDisableParameter',351    'JobTerminateParameter',352    'JobPatchParameter',353    'JobUpdateParameter',354    'PoolEnableAutoScaleParameter',355    'PoolEvaluateAutoScaleParameter',356    'PoolResizeParameter',357    'PoolUpdatePropertiesParameter',358    'PoolUpgradeOSParameter',359    'PoolPatchParameter',360    'TaskUpdateParameter',361    'NodeUpdateUserParameter',362    'NodeRebootParameter',363    'NodeReimageParameter',364    'NodeDisableSchedulingParameter',365    'NodeRemoveParameter',366    'ApplicationListOptions',367    'ApplicationGetOptions',368    'PoolListUsageMetricsOptions',369    'PoolGetAllLifetimeStatisticsOptions',370    'PoolAddOptions',371    'PoolListOptions',372    'PoolDeleteOptions',373    'PoolExistsOptions',374    'PoolGetOptions',375    'PoolPatchOptions',376    'PoolDisableAutoScaleOptions',377    'PoolEnableAutoScaleOptions',378    'PoolEvaluateAutoScaleOptions',379    'PoolResizeOptions',380    'PoolStopResizeOptions',381    'PoolUpdatePropertiesOptions',382    'PoolUpgradeOsOptions',383    'PoolRemoveNodesOptions',384    'AccountListNodeAgentSkusOptions',385    'JobGetAllLifetimeStatisticsOptions',386    'JobDeleteOptions',387    'JobGetOptions',388    'JobPatchOptions',389    'JobUpdateOptions',390    'JobDisableOptions',391    'JobEnableOptions',392    'JobTerminateOptions',393    'JobAddOptions',394    'JobListOptions',395    'JobListFromJobScheduleOptions',396    'JobListPreparationAndReleaseTaskStatusOptions',397    'JobGetTaskCountsOptions',398    'CertificateAddOptions',399    'CertificateListOptions',400    'CertificateCancelDeletionOptions',401    'CertificateDeleteOptions',402    'CertificateGetOptions',403    'FileDeleteFromTaskOptions',404    'FileGetFromTaskOptions',405    'FileGetPropertiesFromTaskOptions',406    'FileDeleteFromComputeNodeOptions',407    'FileGetFromComputeNodeOptions',408    'FileGetPropertiesFromComputeNodeOptions',409    'FileListFromTaskOptions',410    'FileListFromComputeNodeOptions',411    'JobScheduleExistsOptions',412    'JobScheduleDeleteOptions',413    'JobScheduleGetOptions',414    'JobSchedulePatchOptions',415    'JobScheduleUpdateOptions',416    'JobScheduleDisableOptions',417    'JobScheduleEnableOptions',418    'JobScheduleTerminateOptions',419    'JobScheduleAddOptions',420    'JobScheduleListOptions',421    'TaskAddOptions',422    'TaskListOptions',423    'TaskAddCollectionOptions',424    'TaskDeleteOptions',425    'TaskGetOptions',426    'TaskUpdateOptions',427    'TaskListSubtasksOptions',428    'TaskTerminateOptions',429    'TaskReactivateOptions',430    'ComputeNodeAddUserOptions',431    'ComputeNodeDeleteUserOptions',432    'ComputeNodeUpdateUserOptions',433    'ComputeNodeGetOptions',434    'ComputeNodeRebootOptions',435    'ComputeNodeReimageOptions',436    'ComputeNodeDisableSchedulingOptions',437    'ComputeNodeEnableSchedulingOptions',438    'ComputeNodeGetRemoteLoginSettingsOptions',439    'ComputeNodeGetRemoteDesktopOptions',440    'ComputeNodeListOptions',441    'ApplicationSummaryPaged',442    'PoolUsageMetricsPaged',443    'CloudPoolPaged',444    'NodeAgentSkuPaged',445    'CloudJobPaged',446    'JobPreparationAndReleaseTaskExecutionInformationPaged',447    'CertificatePaged',448    'NodeFilePaged',449    'CloudJobSchedulePaged',450    'CloudTaskPaged',451    'ComputeNodePaged',452    'OSType',453    'AccessScope',454    'CertificateState',455    'CertificateFormat',456    'JobAction',457    'DependencyAction',458    'AutoUserScope',459    'ElevationLevel',460    'OutputFileUploadCondition',461    'ComputeNodeFillType',462    'CertificateStoreLocation',463    'CertificateVisibility',464    'CachingType',465    'InboundEndpointProtocol',466    'NetworkSecurityGroupRuleAccess',467    'PoolLifetimeOption',468    'OnAllTasksComplete',469    'OnTaskFailure',470    'JobScheduleState',471    'ErrorCategory',472    'JobState',473    'JobPreparationTaskState',474    'TaskExecutionResult',475    'JobReleaseTaskState',476    'TaskCountValidationStatus',477    'PoolState',478    'AllocationState',479    'TaskState',480    'TaskAddStatus',481    'SubtaskState',482    'StartTaskState',483    'ComputeNodeState',484    'SchedulingState',485    'DisableJobOption',486    'ComputeNodeDeallocationOption',487    'ComputeNodeRebootOption',488    'ComputeNodeReimageOption',489    'DisableComputeNodeSchedulingOption',...ec2_vpc_dhcp_options.py
Source:ec2_vpc_dhcp_options.py  
...222    """223    vpcs = vpc_conn.get_all_vpcs(vpc_ids=[vpc_id])224    if len(vpcs) != 1 or vpcs[0].dhcp_options_id == "default":225        return None226    dhcp_options = vpc_conn.get_all_dhcp_options(dhcp_options_ids=[vpcs[0].dhcp_options_id])227    if len(dhcp_options) != 1:228        return None229    return dhcp_options[0]230def match_dhcp_options(vpc_conn, tags=None, options=None):231    """232    Finds a DHCP Options object that optionally matches the tags and options provided233    """234    dhcp_options = vpc_conn.get_all_dhcp_options()235    for dopts in dhcp_options:236        if (not tags) or get_resource_tags(vpc_conn, dopts.id) == tags:237            if (not options) or dopts.options == options:238                return(True, dopts)239    return(False, None)240def remove_dhcp_options_by_id(vpc_conn, dhcp_options_id):241    associations = vpc_conn.get_all_vpcs(filters={'dhcpOptionsId': dhcp_options_id})242    if len(associations) > 0:243        return False244    else:245        vpc_conn.delete_dhcp_options(dhcp_options_id)246        return True247def main():248    argument_spec = ec2_argument_spec()249    argument_spec.update(dict(250        dhcp_options_id=dict(type='str', default=None),251        domain_name=dict(type='str', default=None),252        dns_servers=dict(type='list', default=None),253        ntp_servers=dict(type='list', default=None),254        netbios_name_servers=dict(type='list', default=None),255        netbios_node_type=dict(type='int', default=None),256        vpc_id=dict(type='str', default=None),257        delete_old=dict(type='bool', default=True),258        inherit_existing=dict(type='bool', default=False),259        tags=dict(type='dict', default=None, aliases=['resource_tags']),260        state=dict(type='str', default='present', choices=['present', 'absent'])261        )262    )263    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)264    params = module.params265    found = False266    changed = False267    new_options = collections.defaultdict(lambda: None)268    region, ec2_url, boto_params = get_aws_connection_info(module)269    connection = connect_to_aws(boto.vpc, region, **boto_params)270    existing_options = None271    # First check if we were given a dhcp_options_id272    if not params['dhcp_options_id']:273        # No, so create new_options from the parameters274        if params['dns_servers'] is not None:275            new_options['domain-name-servers'] = params['dns_servers']276        if params['netbios_name_servers'] is not None:277            new_options['netbios-name-servers'] = params['netbios_name_servers']278        if params['ntp_servers'] is not None:279            new_options['ntp-servers'] = params['ntp_servers']280        if params['domain_name'] is not None:281            # needs to be a list for comparison with boto objects later282            new_options['domain-name'] = [ params['domain_name'] ]283        if params['netbios_node_type'] is not None:284            # needs to be a list for comparison with boto objects later285            new_options['netbios-node-type'] = [ str(params['netbios_node_type']) ]286        # If we were given a vpc_id then we need to look at the options on that287        if params['vpc_id']:288            existing_options = fetch_dhcp_options_for_vpc(connection, params['vpc_id'])289            # if we've been asked to inherit existing options, do that now290            if params['inherit_existing']:291                if existing_options:292                    for option in [ 'domain-name-servers', 'netbios-name-servers', 'ntp-servers', 'domain-name', 'netbios-node-type']:293                        if existing_options.options.get(option) and new_options[option] != [] and (not new_options[option] or [''] == new_options[option]):294                            new_options[option] = existing_options.options.get(option)295            # Do the vpc's dhcp options already match what we're asked for? if so we are done296            if existing_options and new_options == existing_options.options:297                module.exit_json(changed=changed, new_options=new_options, dhcp_options_id=existing_options.id)298        # If no vpc_id was given, or the options don't match then look for an existing set using tags299        found, dhcp_option = match_dhcp_options(connection, params['tags'], new_options)300    # Now let's cover the case where there are existing options that we were told about by id301    # If a dhcp_options_id was supplied we don't look at options inside, just set tags (if given)302    else:303        supplied_options = connection.get_all_dhcp_options(filters={'dhcp-options-id':params['dhcp_options_id']})304        if len(supplied_options) != 1:305            if params['state'] != 'absent':306                module.fail_json(msg=" a dhcp_options_id was supplied, but does not exist")307        else:308            found = True309            dhcp_option = supplied_options[0]310            if params['state'] != 'absent' and params['tags']:311                ensure_tags(connection, dhcp_option.id, params['tags'], False, module.check_mode)312    # Now we have the dhcp options set, let's do the necessary313    # if we found options we were asked to remove then try to do so314    if params['state'] == 'absent':315        if not module.check_mode:316            if found:317                changed = remove_dhcp_options_by_id(connection, dhcp_option.id)318        module.exit_json(changed=changed, new_options={})319    # otherwise if we haven't found the required options we have something to do320    elif not module.check_mode and not found:321        # create some dhcp options if we weren't able to use existing ones322        if not found:323            # Convert netbios-node-type and domain-name back to strings324            if new_options['netbios-node-type']:325                new_options['netbios-node-type'] = new_options['netbios-node-type'][0]326            if new_options['domain-name']:327                new_options['domain-name'] = new_options['domain-name'][0]328            # create the new dhcp options set requested329            dhcp_option = connection.create_dhcp_options(330                new_options['domain-name'],331                new_options['domain-name-servers'],332                new_options['ntp-servers'],333                new_options['netbios-name-servers'],334                new_options['netbios-node-type'])335            changed = True336            if params['tags']:337                ensure_tags(connection, dhcp_option.id, params['tags'], False, module.check_mode)338    # If we were given a vpc_id, then attach the options we now have to that before we finish339    if params['vpc_id'] and not module.check_mode:340        changed = True341        connection.associate_dhcp_options(dhcp_option.id, params['vpc_id'])342        # and remove old ones if that was requested343        if params['delete_old'] and existing_options:344            remove_dhcp_options_by_id(connection, existing_options.id)345    module.exit_json(changed=changed, new_options=new_options, dhcp_options_id=dhcp_option.id)346from ansible.module_utils.basic import *347from ansible.module_utils.ec2 import *348if __name__ == "__main__":...test_options.py
Source:test_options.py  
1# Copyright (c) Twisted Matrix Laboratories.2# See LICENSE for details.3"""4Tests for L{twisted.application.twist._options}.5"""6from sys import stdout, stderr7from twisted.internet import reactor8from twisted.copyright import version9from twisted.python.usage import UsageError10from twisted.logger import LogLevel, textFileLogObserver, jsonFileLogObserver11from twisted.test.proto_helpers import MemoryReactor12from ...reactors import NoSuchReactor13from ...service import ServiceMaker14from ...runner._exit import ExitStatus15from ...runner.test.test_runner import DummyExit16from ...twist import _options17from .._options import TwistOptions18import twisted.trial.unittest19class OptionsTests(twisted.trial.unittest.TestCase):20    """21    Tests for L{TwistOptions}.22    """23    def patchExit(self):24        """25        Patch L{_twist.exit} so we can capture usage and prevent actual exits.26        """27        self.exit = DummyExit()28        self.patch(_options, "exit", self.exit)29    def patchOpen(self):30        """31        Patch L{_options.open} so we can capture usage and prevent actual opens.32        """33        self.opened = []34        def fakeOpen(name, mode=None):35            if name == "nocanopen":36                raise IOError(None, None, name)37            self.opened.append((name, mode))38            return NotImplemented39        self.patch(_options, "openFile", fakeOpen)40    def patchInstallReactor(self):41        """42        Patch C{_options.installReactor} so we can capture usage and prevent43        actual installs.44        """45        self.installedReactors = {}46        def installReactor(name):47            if name != "fusion":48                raise NoSuchReactor()49            reactor = MemoryReactor()50            self.installedReactors[name] = reactor51            return reactor52        self.patch(_options, "installReactor", installReactor)53    def test_synopsis(self):54        """55        L{TwistOptions.getSynopsis} appends arguments.56        """57        options = TwistOptions()58        self.assertTrue(59            options.getSynopsis().endswith(" plugin [plugin_options]")60        )61    def test_version(self):62        """63        L{TwistOptions.opt_version} exits with L{ExitStatus.EX_OK} and prints64        the version.65        """66        self.patchExit()67        options = TwistOptions()68        options.opt_version()69        self.assertEquals(self.exit.status, ExitStatus.EX_OK)70        self.assertEquals(self.exit.message, version)71    def test_reactor(self):72        """73        L{TwistOptions.installReactor} installs the chosen reactor and sets74        the reactor name.75        """76        self.patchInstallReactor()77        options = TwistOptions()78        options.opt_reactor("fusion")79        self.assertEqual(set(self.installedReactors), set(["fusion"]))80        self.assertEquals(options["reactorName"], "fusion")81    def test_installCorrectReactor(self):82        """83        L{TwistOptions.installReactor} installs the chosen reactor after the84        command line options have been parsed.85        """86        self.patchInstallReactor()87        options = TwistOptions()88        options.subCommand = "test-subcommand"89        options.parseOptions(["--reactor=fusion"])90        self.assertEqual(set(self.installedReactors), set(["fusion"]))91    def test_installReactorBogus(self):92        """93        L{TwistOptions.installReactor} raises UsageError if an unknown reactor94        is specified.95        """96        self.patchInstallReactor()97        options = TwistOptions()98        self.assertRaises(UsageError, options.opt_reactor, "coal")99    def test_installReactorDefault(self):100        """101        L{TwistOptions.installReactor} returns the currently installed reactor102        when the default reactor name is specified.103        """104        options = TwistOptions()105        self.assertIdentical(reactor, options.installReactor('default'))106    def test_logLevelValid(self):107        """108        L{TwistOptions.opt_log_level} sets the corresponding log level.109        """110        options = TwistOptions()111        options.opt_log_level("warn")112        self.assertIdentical(options["logLevel"], LogLevel.warn)113    def test_logLevelInvalid(self):114        """115        L{TwistOptions.opt_log_level} with an invalid log level name raises116        UsageError.117        """118        options = TwistOptions()119        self.assertRaises(UsageError, options.opt_log_level, "cheese")120    def _testLogFile(self, name, expectedStream):121        """122        Set log file name and check the selected output stream.123        @param name: The name of the file.124        @param expectedStream: The expected stream.125        """126        options = TwistOptions()127        options.opt_log_file(name)128        self.assertIdentical(options["logFile"], expectedStream)129    def test_logFileStdout(self):130        """131        L{TwistOptions.opt_log_file} given C{"-"} as a file name uses stdout.132        """133        self._testLogFile("-", stdout)134    def test_logFileStderr(self):135        """136        L{TwistOptions.opt_log_file} given C{"+"} as a file name uses stderr.137        """138        self._testLogFile("+", stderr)139    def test_logFileNamed(self):140        """141        L{TwistOptions.opt_log_file} opens the given file name in append mode.142        """143        self.patchOpen()144        options = TwistOptions()145        options.opt_log_file("mylog")146        self.assertEqual([("mylog", "a")], self.opened)147    def test_logFileCantOpen(self):148        """149        L{TwistOptions.opt_log_file} exits with L{ExitStatus.EX_IOERR} if150        unable to open the log file due to an L{EnvironmentError}.151        """152        self.patchExit()153        self.patchOpen()154        options = TwistOptions()155        options.opt_log_file("nocanopen")156        self.assertEquals(self.exit.status, ExitStatus.EX_IOERR)157        self.assertTrue(158            self.exit.message.startswith(159                "Unable to open log file 'nocanopen': "160            )161        )162    def _testLogFormat(self, format, expectedObserver):163        """164        Set log file format and check the selected observer.165        @param format: The format of the file.166        @param expectedObserver: The expected observer.167        """168        options = TwistOptions()169        options.opt_log_format(format)170        self.assertIdentical(171            options["fileLogObserverFactory"], expectedObserver172        )173        self.assertEqual(options["logFormat"], format)174    def test_logFormatText(self):175        """176        L{TwistOptions.opt_log_format} given C{"text"} uses a177        L{textFileLogObserver}.178        """179        self._testLogFormat("text", textFileLogObserver)180    def test_logFormatJSON(self):181        """182        L{TwistOptions.opt_log_format} given C{"text"} uses a183        L{textFileLogObserver}.184        """185        self._testLogFormat("json", jsonFileLogObserver)186    def test_logFormatInvalid(self):187        """188        L{TwistOptions.opt_log_format} given an invalid format name raises189        L{UsageError}.190        """191        options = TwistOptions()192        self.assertRaises(UsageError, options.opt_log_format, "frommage")193    def test_selectDefaultLogObserverNoOverride(self):194        """195        L{TwistOptions.selectDefaultLogObserver} will not override an already196        selected observer.197        """198        self.patchOpen()199        options = TwistOptions()200        options.opt_log_format("text")  # Ask for text201        options.opt_log_file("queso")   # File, not a tty202        options.selectDefaultLogObserver()203        # Because we didn't select a file that is a tty, the default is JSON,204        # but since we asked for text, we should get text.205        self.assertIdentical(206            options["fileLogObserverFactory"], textFileLogObserver207        )208        self.assertEqual(options["logFormat"], "text")209    def test_selectDefaultLogObserverDefaultWithTTY(self):210        """211        L{TwistOptions.selectDefaultLogObserver} will not override an already212        selected observer.213        """214        class TTYFile(object):215            def isatty(self):216                return True217        # stdout may not be a tty, so let's make sure it thinks it is218        self.patch(_options, "stdout", TTYFile())219        options = TwistOptions()220        options.opt_log_file("-")  # stdout, a tty221        options.selectDefaultLogObserver()222        self.assertIdentical(223            options["fileLogObserverFactory"], textFileLogObserver224        )225        self.assertEqual(options["logFormat"], "text")226    def test_selectDefaultLogObserverDefaultWithoutTTY(self):227        """228        L{TwistOptions.selectDefaultLogObserver} will not override an already229        selected observer.230        """231        self.patchOpen()232        options = TwistOptions()233        options.opt_log_file("queso")  # File, not a tty234        options.selectDefaultLogObserver()235        self.assertIdentical(236            options["fileLogObserverFactory"], jsonFileLogObserver237        )238        self.assertEqual(options["logFormat"], "json")239    def test_pluginsType(self):240        """241        L{TwistOptions.plugins} is a mapping of available plug-ins.242        """243        options = TwistOptions()244        plugins = options.plugins245        for name in plugins:246            self.assertIsInstance(name, str)247            self.assertIsInstance(plugins[name], ServiceMaker)248    def test_pluginsIncludeWeb(self):249        """250        L{TwistOptions.plugins} includes a C{"web"} plug-in.251        This is an attempt to verify that something we expect to be in the list252        is in there without enumerating all of the built-in plug-ins.253        """254        options = TwistOptions()255        self.assertIn("web", options.plugins)256    def test_subCommandsType(self):257        """258        L{TwistOptions.subCommands} is an iterable of tuples as expected by259        L{twisted.python.usage.Options}.260        """261        options = TwistOptions()262        for name, shortcut, parser, doc in options.subCommands:263            self.assertIsInstance(name, str)264            self.assertIdentical(shortcut, None)265            self.assertTrue(callable(parser))266            self.assertIsInstance(doc, str)267    def test_subCommandsIncludeWeb(self):268        """269        L{TwistOptions.subCommands} includes a sub-command for every plug-in.270        """271        options = TwistOptions()272        plugins = set(options.plugins)273        subCommands = set(274            name for name, shortcut, parser, doc in options.subCommands275        )276        self.assertEqual(subCommands, plugins)277    def test_postOptionsNoSubCommand(self):278        """279        L{TwistOptions.postOptions} raises L{UsageError} is it has no280        sub-command.281        """282        self.patchInstallReactor()283        options = TwistOptions()...options_test.py
Source:options_test.py  
...100        options = OptionParser()101        options.define('foo', default=1, type=int, callback=values.append)102        options.foo = 2103        self.assertEqual(values, [2])104    def _sample_options(self):105        options = OptionParser()106        options.define('a', default=1)107        options.define('b', default=2)108        return options109    def test_iter(self):110        options = self._sample_options()111        # OptionParsers always define 'help'.112        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))113    def test_getitem(self):114        options = self._sample_options()115        self.assertEqual(1, options['a'])116    def test_setitem(self):117        options = OptionParser()118        options.define('foo', default=1, type=int)119        options['foo'] = 2120        self.assertEqual(options['foo'], 2)121    def test_items(self):122        options = self._sample_options()123        # OptionParsers always define 'help'.124        expected = [('a', 1), ('b', 2), ('help', options.help)]125        actual = sorted(options.items())126        self.assertEqual(expected, actual)127    def test_as_dict(self):128        options = self._sample_options()129        expected = {'a': 1, 'b': 2, 'help': options.help}130        self.assertEqual(expected, options.as_dict())131    def test_group_dict(self):132        options = OptionParser()133        options.define('a', default=1)134        options.define('b', group='b_group', default=2)135        frame = sys._getframe(0)136        this_file = frame.f_code.co_filename137        self.assertEqual(set(['b_group', '', this_file]), options.groups())138        b_group_dict = options.group_dict('b_group')139        self.assertEqual({'b': 2}, b_group_dict)140        self.assertEqual({}, options.group_dict('nonexistent'))141    @unittest.skipIf(mock is None, 'mock package not present')142    def test_mock_patch(self):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
