示例#1
0
def test_optional_survey_question_defaults(survey_spec_factory, question_type,
                                           default, min, max, expect_use,
                                           expect_value):
    spec = survey_spec_factory([
        {
            "required": False,
            "default": default,
            "choices": "orange\nmilk\nchocolate\ncoffee",
            "variable": "c",
            "min": min,
            "max": max,
            "type": question_type
        },
    ])
    jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
    defaulted_extra_vars = jt._update_unified_job_kwargs({}, {})
    element = spec['spec'][0]
    if expect_use:
        assert jt._survey_element_validation(
            element, {element['variable']: element['default']}) == []
    else:
        assert jt._survey_element_validation(
            element, {element['variable']: element['default']})
    if expect_use:
        assert json.loads(
            defaulted_extra_vars['extra_vars'])['c'] == expect_value
    else:
        assert 'c' not in defaulted_extra_vars['extra_vars']
示例#2
0
def test_update_kwargs_survey_invalid_default(survey_spec_factory):
    spec = survey_spec_factory('var2')
    spec['spec'][0]['required'] = False
    spec['spec'][0]['min'] = 3
    spec['spec'][0]['default'] = 1
    jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True, extra_vars="var2: 2")
    defaulted_extra_vars = jt._update_unified_job_kwargs({}, {})
    assert 'extra_vars' in defaulted_extra_vars
    # Make sure we did not set the invalid default of 1
    assert json.loads(defaulted_extra_vars['extra_vars'])['var2'] == 2
示例#3
0
 def test_jt_extra_vars_counting(self, provided_vars, valid):
     jt = JobTemplate(name='foo',
                      extra_vars={'tmpl_var': 'bar'},
                      project=Project(),
                      project_id=42,
                      playbook='helloworld.yml',
                      inventory=Inventory(),
                      inventory_id=42)
     prompted_fields, ignored_fields, errors = jt._accept_or_ignore_job_kwargs(
         extra_vars=provided_vars)
     self.process_vars_and_assert(jt, provided_vars, valid)
示例#4
0
    def get_serializer_context(self, *args, **kwargs):
        full_context = super(OrganizationDetail,
                             self).get_serializer_context(*args, **kwargs)

        if not hasattr(self, 'kwargs') or 'pk' not in self.kwargs:
            return full_context
        org_id = int(self.kwargs['pk'])

        org_counts = {}
        access_kwargs = {
            'accessor': self.request.user,
            'role_field': 'read_role'
        }
        direct_counts = Organization.objects.filter(id=org_id).annotate(
            users=Count('member_role__members', distinct=True),
            admins=Count('admin_role__members',
                         distinct=True)).values('users', 'admins')

        if not direct_counts:
            return full_context

        org_counts = direct_counts[0]
        org_counts['inventories'] = Inventory.accessible_objects(
            **access_kwargs).filter(organization__id=org_id).count()
        org_counts['teams'] = Team.accessible_objects(**access_kwargs).filter(
            organization__id=org_id).count()
        org_counts['projects'] = Project.accessible_objects(
            **access_kwargs).filter(organization__id=org_id).count()
        org_counts['job_templates'] = JobTemplate.accessible_objects(
            **access_kwargs).filter(organization__id=org_id).count()

        full_context['related_field_counts'] = {}
        full_context['related_field_counts'][org_id] = org_counts

        return full_context
示例#5
0
def job(container_group):
    return Job(pk=1,
               id=1,
               project=Project(),
               instance_group=container_group,
               inventory=Inventory(),
               job_template=JobTemplate(id=1, name='foo'))
示例#6
0
def test_clean_extra_data_other_job(mocker):
    jt = JobTemplate()
    schedule = Schedule(unified_job_template=jt)
    schedule._clean_extra_data_system_jobs = mocker.MagicMock()

    schedule.clean_extra_data()

    schedule._clean_extra_data_system_jobs.assert_not_called()
示例#7
0
def test_survey_encryption_defaults(survey_spec_factory, question_type, default, maxlen, kwargs, expected):
    spec = survey_spec_factory([
        {
            "required": True,
            "variable": "x",
            "min": 0,
            "max": maxlen,
            "type": question_type
        },
    ])
    if default is not None:
        spec['spec'][0]['default'] = default
    else:
        spec['spec'][0].pop('default', None)
    jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
    extra_vars = json.loads(jt._update_unified_job_kwargs({}, kwargs).get('extra_vars'))
    assert extra_vars == expected
 def jt(self, survey_spec_factory):
     return JobTemplate(
         name='fake-jt',
         survey_enabled=True,
         survey_spec=survey_spec_factory(variables='var1', default_type='password'),
         project=Project('fake-proj'), project_id=42,
         inventory=Inventory('fake-inv'), inventory_id=42
     )
示例#9
0
    def get(self, request, format=None):
        '''Return various sitewide configuration settings'''

        if request.user.is_superuser or request.user.is_system_auditor:
            license_data = get_license(show_key=True)
        else:
            license_data = get_license(show_key=False)
        if not license_data.get('valid_key', False):
            license_data = {}
        if license_data and 'features' in license_data and 'activity_streams' in license_data[
                'features']:
            # FIXME: Make the final setting value dependent on the feature?
            license_data['features'][
                'activity_streams'] &= settings.ACTIVITY_STREAM_ENABLED

        pendo_state = settings.PENDO_TRACKING_STATE if settings.PENDO_TRACKING_STATE in (
            'off', 'anonymous', 'detailed') else 'off'

        data = dict(
            time_zone=settings.TIME_ZONE,
            license_info=license_data,
            version=get_awx_version(),
            ansible_version=get_ansible_version(),
            eula=render_to_string("eula.md") if
            license_data.get('license_type', 'UNLICENSED') != 'open' else '',
            analytics_status=pendo_state,
            analytics_collectors=all_collectors(),
            become_methods=PRIVILEGE_ESCALATION_METHODS,
        )

        # If LDAP is enabled, user_ldap_fields will return a list of field
        # names that are managed by LDAP and should be read-only for users with
        # a non-empty ldap_dn attribute.
        if getattr(settings, 'AUTH_LDAP_SERVER_URI', None):
            user_ldap_fields = ['username', 'password']
            user_ldap_fields.extend(
                getattr(settings, 'AUTH_LDAP_USER_ATTR_MAP', {}).keys())
            user_ldap_fields.extend(
                getattr(settings, 'AUTH_LDAP_USER_FLAGS_BY_GROUP', {}).keys())
            data['user_ldap_fields'] = user_ldap_fields

        if request.user.is_superuser \
                or request.user.is_system_auditor \
                or Organization.accessible_objects(request.user, 'admin_role').exists() \
                or Organization.accessible_objects(request.user, 'auditor_role').exists() \
                or Organization.accessible_objects(request.user, 'project_admin_role').exists():
            data.update(
                dict(project_base_dir=settings.PROJECTS_ROOT,
                     project_local_paths=Project.get_local_path_choices(),
                     custom_virtualenvs=get_custom_venv_choices()))
        elif JobTemplate.accessible_objects(request.user,
                                            'admin_role').exists():
            data['custom_virtualenvs'] = get_custom_venv_choices()

        return Response(data)
示例#10
0
 def test_project_update_metavars(self):
     data = Job(name='fake-job',
                pk=40,
                id=40,
                launch_type='manual',
                project=Project(name='jobs-sync', scm_revision='12345444'),
                job_template=JobTemplate(name='jobs-jt', id=92,
                                         pk=92)).awx_meta_vars()
     assert data['awx_project_revision'] == '12345444'
     assert 'tower_job_template_id' in data
     assert data['tower_job_template_id'] == 92
     assert data['tower_job_template_name'] == 'jobs-jt'
示例#11
0
def test_launch_config_has_unprompted_vars(survey_spec_factory):
    jt = JobTemplate(survey_enabled=True,
                     survey_spec=survey_spec_factory(
                         ['question1', 'question2']))
    unprompted_config = JobLaunchConfig(extra_data={
        'question1': 'foobar',
        'question4': 'foobar'
    })
    assert unprompted_config.has_unprompted(jt)
    allowed_config = JobLaunchConfig(extra_data={
        'question1': 'foobar',
        'question2': 'foobar'
    })
    assert not allowed_config.has_unprompted(jt)
示例#12
0
 def test_project_update_metavars(self):
     data = Job(
         name='fake-job',
         pk=40,
         id=40,
         launch_type='manual',
         project=Project(name='jobs-sync', scm_revision='12345444'),
         job_template=JobTemplate(name='jobs-jt', id=92, pk=92),
     ).awx_meta_vars()
     for name in JOB_VARIABLE_PREFIXES:
         assert data['{}_project_revision'.format(name)] == '12345444'
         assert '{}_job_template_id'.format(name) in data
         assert data['{}_job_template_id'.format(name)] == 92
         assert data['{}_job_template_name'.format(name)] == 'jobs-jt'
示例#13
0
def test_cloud_credential_type_mutability(patch, organization, admin, credentialtype_ssh,
                                          credentialtype_aws):
    cred = Credential(
        credential_type=credentialtype_aws,
        name='Best credential ever',
        organization=organization,
        inputs={
            'username': u'jim',
            'password': u'pass'
        }
    )
    cred.save()

    jt = JobTemplate()
    jt.save()
    jt.credentials.add(cred)

    def _change_credential_type():
        return patch(
            reverse('api:credential_detail', kwargs={'pk': cred.pk}),
            {
                'credential_type': credentialtype_ssh.pk,
                'inputs': {
                    'username': u'jim',
                    'password': u'pass'
                }
            },
            admin
        )

    response = _change_credential_type()
    assert response.status_code == 400
    expected = ['You cannot change the credential type of the credential, '
                'as it may break the functionality of the resources using it.']
    assert response.data['credential_type'] == expected

    response = patch(
        reverse('api:credential_detail', kwargs={'pk': cred.pk}),
        {'name': 'Worst credential ever'},
        admin
    )
    assert response.status_code == 200
    assert Credential.objects.get(pk=cred.pk).name == 'Worst credential ever'

    jt.delete()
    response = _change_credential_type()
    assert response.status_code == 200
示例#14
0
def test_display_survey_spec_encrypts_default(survey_spec_factory):
    spec = survey_spec_factory('var2')
    spec['spec'][0]['type'] = 'password'
    spec['spec'][0]['default'] = 'some-default'
    jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
    assert jt.display_survey_spec()['spec'][0]['default'] == '$encrypted$'
示例#15
0
def job_template(project):
    jt = JobTemplate(name='unit-test-jt', project=project)
    apply_fake_roles(jt)
    return jt
示例#16
0
文件: fixtures.py 项目: zhl003/awx
def mk_job_template(name,
                    job_type='run',
                    organization=None,
                    inventory=None,
                    credential=None,
                    network_credential=None,
                    cloud_credential=None,
                    persisted=True,
                    extra_vars='',
                    project=None,
                    spec=None):
    if extra_vars:
        extra_vars = json.dumps(extra_vars)

    jt = JobTemplate(name=name,
                     job_type=job_type,
                     extra_vars=extra_vars,
                     playbook='helloworld.yml')

    jt.inventory = inventory
    if jt.inventory is None:
        jt.ask_inventory_on_launch = True

    if persisted and credential:
        jt.save()
        jt.credentials.add(credential)
        if jt.machine_credential is None:
            jt.ask_credential_on_launch = True

    jt.project = project

    jt.survey_spec = spec
    if jt.survey_spec is not None:
        jt.survey_enabled = True

    if persisted:
        jt.save()
        if cloud_credential:
            cloud_credential.save()
            jt.credentials.add(cloud_credential)
        if network_credential:
            network_credential.save()
            jt.credentials.add(network_credential)
        jt.save()
    return jt
示例#17
0
    response = put(reverse('api:credential_detail', kwargs={'pk': cred.pk}),
                   params, admin)
    assert response.status_code == 200

    cred = Credential.objects.all()[:1].get()
    assert cred.inputs['username'] == 'joe'
    assert 'password' not in cred.inputs


@pytest.mark.django_db
@pytest.mark.parametrize(
    'relation, related_obj',
    [
        ['ad_hoc_commands', AdHocCommand()],
        ['unifiedjobs', Job()],
        ['unifiedjobtemplates', JobTemplate()],
        ['unifiedjobtemplates',
         InventorySource(source='ec2')],
        ['projects', Project()],
        ['workflowjobnodes', WorkflowJobNode()],
    ],
)
def test_credential_type_mutability(patch, organization, admin,
                                    credentialtype_ssh, credentialtype_aws,
                                    relation, related_obj):
    cred = Credential(credential_type=credentialtype_ssh,
                      name='Best credential ever',
                      organization=organization,
                      inputs={
                          'username': u'jim',
                          'password': u'pass'