function
stringlengths 11
56k
| repo_name
stringlengths 5
60
| features
sequence |
---|---|---|
def setUp(self):
super().setUp()
self.url = reverse("accounts_api", kwargs={'username': self.user.username})
self.search_api_url = reverse("accounts_search_emails_api") | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def _verify_full_shareable_account_response(self, response, account_privacy=None, badges_enabled=False):
"""
Verify that the shareable fields from the account are returned
"""
data = response.data
assert 12 == len(data)
# public fields (3)
assert account_privacy == data['account_privacy']
self._verify_profile_image_data(data, True)
assert self.user.username == data['username']
# additional shareable fields (8)
assert TEST_BIO_VALUE == data['bio']
assert 'US' == data['country']
assert data['date_joined'] is not None
assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies']
assert 'm' == data['level_of_education']
assert data['social_links'] is not None
assert data['time_zone'] is None
assert badges_enabled == data['accomplishments_shared'] | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def _verify_full_account_response(self, response, requires_parental_consent=False, year_of_birth=2000):
"""
Verify that all account fields are returned (even those that are not shareable).
"""
data = response.data
assert self.FULL_RESPONSE_FIELD_COUNT == len(data)
# public fields (3)
expected_account_privacy = (
PRIVATE_VISIBILITY if requires_parental_consent else
UserPreference.get_value(self.user, 'account_privacy')
)
assert expected_account_privacy == data['account_privacy']
self._verify_profile_image_data(data, not requires_parental_consent)
assert self.user.username == data['username']
# additional shareable fields (8)
assert TEST_BIO_VALUE == data['bio']
assert 'US' == data['country']
assert data['date_joined'] is not None
assert data['last_login'] is not None
assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies']
assert 'm' == data['level_of_education']
assert data['social_links'] is not None
assert UserPreference.get_value(self.user, 'time_zone') == data['time_zone']
assert data['accomplishments_shared'] is not None
assert ((self.user.first_name + ' ') + self.user.last_name) == data['name']
# additional admin fields (13)
assert self.user.email == data['email']
assert self.user.id == data['id']
assert self.VERIFIED_NAME == data['verified_name']
assert data['extended_profile'] is not None
assert 'MA' == data['state']
assert 'f' == data['gender']
assert 'world peace' == data['goals']
assert data['is_active']
assert 'Park Ave' == data['mailing_address']
assert requires_parental_consent == data['requires_parental_consent']
assert data['secondary_email'] is None
assert data['secondary_email_enabled'] is None
assert year_of_birth == data['year_of_birth'] | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_unsupported_methods(self):
"""
Test that DELETE, POST, and PUT are not supported.
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
assert 405 == self.client.put(self.url).status_code
assert 405 == self.client.post(self.url).status_code
assert 405 == self.client.delete(self.url).status_code | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_get_account_unknown_user(self, api_client, user):
"""
Test that requesting a user who does not exist returns a 404.
"""
client = self.login_client(api_client, user)
response = client.get(reverse("accounts_api", kwargs={'username': "does_not_exist"}))
assert 404 == response.status_code | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_regsitration_activation_key(self, api_client, user):
"""
Test that registration activation key has a value.
UserFactory does not auto-generate registration object for the test users.
It is created only for users that signup via email/API. Therefore, activation key has to be tested manually.
"""
self.create_user_registration(self.user)
client = self.login_client(api_client, user)
response = self.send_get(client)
assert response.data["activation_key"] is not None | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_unsuccessful_get_account_by_email(self):
"""
Test that request using email by a normal user fails to retrieve Account Info.
"""
api_client = "client"
user = "user"
client = self.login_client(api_client, user)
self.create_mock_profile(self.user)
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY)
response = self.send_get(
client, query_parameters=f'email={self.user.email}', expected_status=status.HTTP_403_FORBIDDEN
)
assert response.data.get('detail') == 'You do not have permission to perform this action.' | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_unsuccessful_get_account_by_user_id(self):
"""
Test that requesting using lms user id by a normal user fails to retrieve Account Info.
"""
api_client = "client"
user = "user"
url = reverse("accounts_detail_api")
client = self.login_client(api_client, user)
self.create_mock_profile(self.user)
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY)
response = client.get(url + f'?lms_user_id={self.user.id}')
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.data.get('detail') == 'You do not have permission to perform this action.' | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_get_account_by_user_id_non_integer(self, non_integer_id):
"""
Test that request using a non-integer lms user id by a staff user fails to retrieve Account Info.
"""
api_client = "staff_client"
user = "staff_user"
url = reverse("accounts_detail_api")
client = self.login_client(api_client, user)
self.create_mock_profile(self.user)
self.create_mock_verified_name(self.user)
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY)
response = client.get(url + f'?lms_user_id={non_integer_id}')
assert response.status_code == status.HTTP_400_BAD_REQUEST | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_search_emails_with_non_staff_user(self):
client = self.login_client('client', 'user')
json_data = {'emails': [self.user.email]}
response = self.post_search_api(client, json_data=json_data, expected_status=404)
assert response.data == {
'developer_message': "not_found",
'user_message': "Not Found"
} | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_search_emails_with_invalid_param(self):
client = self.login_client('staff_client', 'staff_user')
json_data = {'invalid_key': [self.user.email]}
response = self.post_search_api(client, json_data=json_data, expected_status=400)
assert response.data == {
'developer_message': "'emails' field is required",
'user_message': "'emails' field is required"
} | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_get_account_different_user_visible(self):
"""
Test that a client (logged in) can only get the shareable fields for a different user.
This is the case when default_visibility is set to "all_users".
"""
self.different_client.login(username=self.different_user.username, password=TEST_PASSWORD)
self.create_mock_profile(self.user)
with self.assertNumQueries(self.TOTAL_QUERY_COUNT):
response = self.send_get(self.different_client)
self._verify_full_shareable_account_response(response, account_privacy=ALL_USERS_VISIBILITY) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_get_account_different_user_private(self):
"""
Test that a client (logged in) can only get the shareable fields for a different user.
This is the case when default_visibility is set to "private".
"""
self.different_client.login(username=self.different_user.username, password=TEST_PASSWORD)
self.create_mock_profile(self.user)
with self.assertNumQueries(self.TOTAL_QUERY_COUNT):
response = self.send_get(self.different_client)
self._verify_private_account_response(response) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_get_account_private_visibility(self, api_client, requesting_username, preference_visibility):
"""
Test the return from GET based on user visibility setting.
"""
def verify_fields_visible_to_all_users(response):
"""
Confirms that private fields are private, and public/shareable fields are public/shareable
"""
if preference_visibility == PRIVATE_VISIBILITY:
self._verify_private_account_response(response)
else:
self._verify_full_shareable_account_response(response, ALL_USERS_VISIBILITY, badges_enabled=True)
client = self.login_client(api_client, requesting_username)
# Update user account visibility setting.
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, preference_visibility)
self.create_mock_profile(self.user)
self.create_mock_verified_name(self.user)
response = self.send_get(client)
if requesting_username == "different_user":
verify_fields_visible_to_all_users(response)
else:
self._verify_full_account_response(response)
# Verify how the view parameter changes the fields that are returned.
response = self.send_get(client, query_parameters='view=shared')
verify_fields_visible_to_all_users(response)
response = self.send_get(client, query_parameters=f'view=shared&username={self.user.username}')
verify_fields_visible_to_all_users(response) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_custom_visibility_over_age(self, api_client, requesting_username):
self.create_mock_profile(self.user)
self.create_mock_verified_name(self.user)
# set user's custom visibility preferences
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, CUSTOM_VISIBILITY)
shared_fields = ("bio", "language_proficiencies", "name")
for field_name in shared_fields:
set_user_preference(self.user, f"visibility.{field_name}", ALL_USERS_VISIBILITY)
# make API request
client = self.login_client(api_client, requesting_username)
response = self.send_get(client)
# verify response
if requesting_username == "different_user":
data = response.data
assert 6 == len(data)
# public fields
assert self.user.username == data['username']
assert UserPreference.get_value(self.user, 'account_privacy') == data['account_privacy']
self._verify_profile_image_data(data, has_profile_image=True)
# custom shared fields
assert TEST_BIO_VALUE == data['bio']
assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies']
assert ((self.user.first_name + ' ') + self.user.last_name) == data['name']
else:
self._verify_full_account_response(response) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_custom_visibility_under_age(self, api_client, requesting_username):
self.create_mock_profile(self.user)
self.create_mock_verified_name(self.user)
year_of_birth = self._set_user_age_to_10_years(self.user)
# set user's custom visibility preferences
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, CUSTOM_VISIBILITY)
shared_fields = ("bio", "language_proficiencies")
for field_name in shared_fields:
set_user_preference(self.user, f"visibility.{field_name}", ALL_USERS_VISIBILITY)
# make API request
client = self.login_client(api_client, requesting_username)
response = self.send_get(client)
# verify response
if requesting_username == "different_user":
self._verify_private_account_response(response, requires_parental_consent=True)
else:
self._verify_full_account_response(
response,
requires_parental_consent=True,
year_of_birth=year_of_birth,
) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def verify_get_own_information(queries):
"""
Internal helper to perform the actual assertions
"""
with self.assertNumQueries(queries):
response = self.send_get(self.client)
data = response.data
assert self.FULL_RESPONSE_FIELD_COUNT == len(data)
assert self.user.username == data['username']
assert ((self.user.first_name + ' ') + self.user.last_name) == data['name']
for empty_field in ("year_of_birth", "level_of_education", "mailing_address", "bio"):
assert data[empty_field] is None
assert data['country'] is None
assert data['state'] is None
assert 'm' == data['gender']
assert 'Learn a lot' == data['goals']
assert self.user.email == data['email']
assert self.user.id == data['id']
assert data['date_joined'] is not None
assert data['last_login'] is not None
assert self.user.is_active == data['is_active']
self._verify_profile_image_data(data, False)
assert data['requires_parental_consent']
assert [] == data['language_proficiencies']
assert PRIVATE_VISIBILITY == data['account_privacy']
assert data['time_zone'] is None
# Badges aren't on by default, so should not be present.
assert data['accomplishments_shared'] is False | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_get_account_empty_string(self):
"""
Test the conversion of empty strings to None for certain fields.
"""
legacy_profile = UserProfile.objects.get(id=self.user.id)
legacy_profile.country = ""
legacy_profile.state = ""
legacy_profile.level_of_education = ""
legacy_profile.gender = ""
legacy_profile.bio = ""
legacy_profile.save()
self.client.login(username=self.user.username, password=TEST_PASSWORD)
with self.assertNumQueries(25):
response = self.send_get(self.client)
for empty_field in ("level_of_education", "gender", "country", "state", "bio",):
assert response.data[empty_field] is None | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_account_disallowed_user(self, api_client, user):
"""
Test that a client cannot call PATCH on a different client's user account (even with
is_staff access).
"""
client = self.login_client(api_client, user)
self.send_patch(client, {}, expected_status=403) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_account_unknown_user(self, api_client, user):
"""
Test that trying to update a user who does not exist returns a 403.
"""
client = self.login_client(api_client, user)
response = client.patch(
reverse("accounts_api", kwargs={'username': "does_not_exist"}),
data=json.dumps({}), content_type="application/merge-patch+json"
)
assert 403 == response.status_code | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None):
"""
Test the behavior of patch, when using the correct content_type.
"""
client = self.login_client("client", "user")
if field == 'account_privacy':
# Ensure the user has birth year set, and is over 13, so
# account_privacy behaves normally
legacy_profile = UserProfile.objects.get(id=self.user.id)
legacy_profile.year_of_birth = 2000
legacy_profile.save()
response = self.send_patch(client, {field: value})
assert value == response.data[field]
if fails_validation_value:
error_response = self.send_patch(client, {field: fails_validation_value}, expected_status=400)
expected_user_message = 'This value is invalid.'
if field == 'bio':
expected_user_message = "The about me field must be at most 300 characters long."
assert expected_user_message == error_response.data['field_errors'][field]['user_message']
assert "Value '{value}' is not valid for field '{field}': {messages}".format(
value=fails_validation_value,
field=field,
messages=[developer_validation_message]
) == error_response.data['field_errors'][field]['developer_message']
elif field != "account_privacy":
# If there are no values that would fail validation, then empty string should be supported;
# except for account_privacy, which cannot be an empty string.
response = self.send_patch(client, {field: ""})
assert '' == response.data[field] | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_account_noneditable(self):
"""
Tests the behavior of patch when a read-only field is attempted to be edited.
"""
client = self.login_client("client", "user")
def verify_error_response(field_name, data):
"""
Internal helper to check the error messages returned
"""
assert 'This field is not editable via this API' == data['field_errors'][field_name]['developer_message']
assert "The '{}' field cannot be edited.".format(
field_name
) == data['field_errors'][field_name]['user_message']
for field_name in ["username", "date_joined", "is_active", "profile_image", "requires_parental_consent"]:
response = self.send_patch(client, {field_name: "will_error", "gender": "o"}, expected_status=400)
verify_error_response(field_name, response.data)
# Make sure that gender did not change.
response = self.send_get(client)
assert 'm' == response.data['gender']
# Test error message with multiple read-only items
response = self.send_patch(client, {"username": "will_error", "date_joined": "xx"}, expected_status=400)
assert 2 == len(response.data['field_errors'])
verify_error_response("username", response.data)
verify_error_response("date_joined", response.data) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_account_empty_string(self):
"""
Tests the behavior of patch when attempting to set fields with a select list of options to the empty string.
Also verifies the behaviour when setting to None.
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
for field_name in ["gender", "level_of_education", "country", "state"]:
response = self.send_patch(self.client, {field_name: ""})
# Although throwing a 400 might be reasonable, the default DRF behavior with ModelSerializer
# is to convert to None, which also seems acceptable (and is difficult to override).
assert response.data[field_name] is None
# Verify that the behavior is the same for sending None.
response = self.send_patch(self.client, {field_name: ""})
assert response.data[field_name] is None | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def get_name_change_info(expected_entries):
"""
Internal method to encapsulate the retrieval of old names used
"""
legacy_profile = UserProfile.objects.get(id=self.user.id)
name_change_info = legacy_profile.get_meta()["old_names"]
assert expected_entries == len(name_change_info)
return name_change_info | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_email(self):
"""
Test that the user can request an email change through the accounts API.
Full testing of the helper method used (do_email_change_request) exists in the package with the code.
Here just do minimal smoke testing.
"""
client = self.login_client("client", "user")
old_email = self.user.email
new_email = "newemail@example.com"
response = self.send_patch(client, {"email": new_email, "goals": "change my email"})
# Since request is multi-step, the email won't change on GET immediately (though goals will update).
assert old_email == response.data['email']
assert 'change my email' == response.data['goals']
# Now call the method that will be invoked with the user clicks the activation key in the received email.
# First we must get the activation key that was sent.
pending_change = PendingEmailChange.objects.filter(user=self.user)
assert 1 == len(pending_change)
activation_key = pending_change[0].activation_key
confirm_change_url = reverse(
"confirm_email_change", kwargs={'key': activation_key}
)
response = self.client.post(confirm_change_url)
assert 200 == response.status_code
get_response = self.send_get(client)
assert new_email == get_response.data['email'] | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_invalid_email(self, bad_email):
"""
Test a few error cases for email validation (full test coverage lives with do_email_change_request).
"""
client = self.login_client("client", "user")
# Try changing to an invalid email to make sure error messages are appropriately returned.
error_response = self.send_patch(client, {"email": bad_email}, expected_status=400)
field_errors = error_response.data["field_errors"]
assert "Error thrown from validate_new_email: 'Valid e-mail address required.'" == \
field_errors['email']['developer_message']
assert 'Valid e-mail address required.' == field_errors['email']['user_message'] | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_duplicate_email(self, do_email_change_request):
"""
Test that same success response will be sent to user even if the given email already used.
"""
existing_email = "same@example.com"
UserFactory.create(email=existing_email)
client = self.login_client("client", "user")
# Try changing to an existing email to make sure no error messages returned.
response = self.send_patch(client, {"email": existing_email})
assert 200 == response.status_code
# Verify that no actual request made for email change
assert not do_email_change_request.called | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_invalid_language_proficiencies(self, patch_value, expected_error_message):
"""
Verify we handle error cases when patching the language_proficiencies
field.
"""
expected_error_message = str(expected_error_message).replace('unicode', 'str')
client = self.login_client("client", "user")
response = self.send_patch(client, {"language_proficiencies": patch_value}, expected_status=400)
assert response.data['field_errors']['language_proficiencies']['developer_message'] == \
f"Value '{patch_value}' is not valid for field 'language_proficiencies': {expected_error_message}" | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_patch_serializer_save_fails(self, serializer_save):
"""
Test that AccountUpdateErrors are passed through to the response.
"""
serializer_save.side_effect = [Exception("bummer"), None]
self.client.login(username=self.user.username, password=TEST_PASSWORD)
error_response = self.send_patch(self.client, {"goals": "save an account field"}, expected_status=400)
assert "Error thrown when saving account updates: 'bummer'" == error_response.data['developer_message']
assert error_response.data['user_message'] is None | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_convert_relative_profile_url(self):
"""
Test that when TEST_PROFILE_IMAGE_BACKEND['base_url'] begins
with a '/', the API generates the full URL to profile images based on
the URL of the request.
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
response = self.send_get(self.client)
assert response.data['profile_image'] == \
{'has_image': False,
'image_url_full': 'http://testserver/static/default_50.png',
'image_url_small': 'http://testserver/static/default_10.png'} | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_parental_consent(self, api_client, requesting_username, has_full_access):
"""
Verifies that under thirteens never return a public profile.
"""
client = self.login_client(api_client, requesting_username)
year_of_birth = self._set_user_age_to_10_years(self.user)
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, ALL_USERS_VISIBILITY)
# Verify that the default view is still private (except for clients with full access)
response = self.send_get(client)
if has_full_access:
data = response.data
assert self.FULL_RESPONSE_FIELD_COUNT == len(data)
assert self.user.username == data['username']
assert ((self.user.first_name + ' ') + self.user.last_name) == data['name']
assert self.user.email == data['email']
assert self.user.id == data['id']
assert year_of_birth == data['year_of_birth']
for empty_field in ("country", "level_of_education", "mailing_address", "bio", "state",):
assert data[empty_field] is None
assert 'm' == data['gender']
assert 'Learn a lot' == data['goals']
assert data['is_active']
assert data['date_joined'] is not None
assert data['last_login'] is not None
self._verify_profile_image_data(data, False)
assert data['requires_parental_consent']
assert PRIVATE_VISIBILITY == data['account_privacy']
else:
self._verify_private_account_response(response, requires_parental_consent=True)
# Verify that the shared view is still private
response = self.send_get(client, query_parameters='view=shared')
self._verify_private_account_response(response, requires_parental_consent=True) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def setUp(self):
super().setUp()
self.client = APIClient()
self.user = UserFactory.create(password=TEST_PASSWORD)
self.url = reverse("accounts_api", kwargs={'username': self.user.username}) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_update_account_settings_rollback(self, mock_email_change):
"""
Verify that updating account settings is transactional when a failure happens.
"""
# Send a PATCH request with updates to both profile information and email.
# Throw an error from the method that is used to process the email change request
# (this is the last thing done in the api method). Verify that the profile did not change.
mock_email_change.side_effect = [ValueError, "mock value error thrown"]
self.client.login(username=self.user.username, password=TEST_PASSWORD)
old_email = self.user.email
json_data = {"email": "foo@bar.com", "gender": "o"}
response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json")
assert 400 == response.status_code
# Verify that GET returns the original preferences
response = self.client.get(self.url)
data = response.data
assert old_email == data['email']
assert 'm' == data['gender'] | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def setUp(self):
super().setUp()
self.url = reverse('name_change') | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_unauthenticated(self):
"""
Test that a name change request fails for an unauthenticated user.
"""
self.send_post(self.client, {'name': 'New Name'}, expected_status=401) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_blank_name(self):
"""
Test that a blank name string fails.
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
self.send_post(self.client, {'name': ''}, expected_status=400) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_fails_validation(self, invalid_name):
"""
Test that an invalid name will return an error.
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
self.send_post(
self.client,
{'name': invalid_name},
expected_status=400
) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def setUp(self):
super().setUp()
self.service_user = UserFactory(username=self.SERVICE_USERNAME)
self.url = reverse("username_replacement") | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def call_api(self, user, data):
""" Helper function to call API with data """
data = json.dumps(data)
headers = self.build_jwt_headers(user)
return self.client.post(self.url, data, content_type='application/json', **headers) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_bad_schema(self, mapping_data):
""" Verify the endpoint rejects bad data schema """
data = {
"username_mappings": mapping_data
}
response = self.call_api(self.service_user, data)
assert response.status_code == 400 | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def _checkInput(index):
if index < 0:
raise ValueError("Indice negativo non supportato [{}]".format(index))
elif type(index) != int:
raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) | feroda/lessons-python4beginners | [
2,
12,
2,
3,
1472811971
] |
def fib_from_list(index):
_checkInput(index)
serie = [0,1,1,2,3,5,8]
return serie[index] | feroda/lessons-python4beginners | [
2,
12,
2,
3,
1472811971
] |
def recursion(index):
if index <= 1:
return index
return recursion(index - 1) + recursion(index - 2) | feroda/lessons-python4beginners | [
2,
12,
2,
3,
1472811971
] |
def fib_from_recursion_func(index):
_checkInput(index)
return recursion(index) | feroda/lessons-python4beginners | [
2,
12,
2,
3,
1472811971
] |
def setup(self):
self.robot.light[0].units = "SCALED" | emilydolson/forestcat | [
2,
2,
2,
2,
1370887123
] |
def INIT(engine):
if engine.robot.type not in ['K-Team', 'Pyrobot']:
raise "Robot should have light sensors!"
return Vehicle('Braitenberg2a', engine) | emilydolson/forestcat | [
2,
2,
2,
2,
1370887123
] |
def emit(self, record):
pass | vert-x3/vertx-web | [
1019,
499,
1019,
184,
1415952920
] |
def enableTrace(traceable, handler = logging.StreamHandler()):
"""
turn on/off the traceability.
traceable: boolean value. if set True, traceability is enabled.
"""
global _traceEnabled
_traceEnabled = traceable
if traceable:
_logger.addHandler(handler)
_logger.setLevel(logging.DEBUG) | vert-x3/vertx-web | [
1019,
499,
1019,
184,
1415952920
] |
def error(msg):
_logger.error(msg) | vert-x3/vertx-web | [
1019,
499,
1019,
184,
1415952920
] |
def debug(msg):
_logger.debug(msg) | vert-x3/vertx-web | [
1019,
499,
1019,
184,
1415952920
] |
def isEnabledForError():
return _logger.isEnabledFor(logging.ERROR) | vert-x3/vertx-web | [
1019,
499,
1019,
184,
1415952920
] |
def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"):
super(TarThread, self).__init__(self.__class__.__name__, compression)
self.compression_method = compression
self.backup_dir = backup_dir
self.output_file = output_file
self.verbose = verbose
self.binary = binary
self._command = None | Percona-Lab/mongodb_consistent_backup | [
274,
82,
274,
33,
1466066641
] |
def run(self):
if os.path.isdir(self.backup_dir):
if not os.path.isfile(self.output_file):
try:
backup_base_dir = os.path.dirname(self.backup_dir)
backup_base_name = os.path.basename(self.backup_dir)
log_msg = "Archiving directory: %s" % self.backup_dir
cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"]
if self.do_gzip():
log_msg = "Archiving and compressing directory: %s" % self.backup_dir
cmd_flags.append("-z")
cmd_flags.append(backup_base_name)
logging.info(log_msg)
self.running = True
self._command = LocalCommand(self.binary, cmd_flags, self.verbose)
self.exit_code = self._command.run()
except Exception, e:
return self.result(False, "Failed archiving file: %s!" % self.output_file, e)
finally:
self.running = False
self.stopped = True
self.completed = True
else:
return self.result(False, "Output file: %s already exists!" % self.output_file, None)
return self.result(True, "Archiving successful.", None) | Percona-Lab/mongodb_consistent_backup | [
274,
82,
274,
33,
1466066641
] |
def garch(X: Matrix,
kmax: int,
momentum: float,
start_stepsize: float,
end_stepsize: float,
start_vicinity: float,
end_vicinity: float,
sim_seed: int,
verbose: bool):
"""
:param X: The input Matrix to apply Arima on.
:param kmax: Number of iterations
:param momentum: Momentum for momentum-gradient descent (set to 0 to deactivate)
:param start_stepsize: Initial gradient-descent stepsize
:param end_stepsize: gradient-descent stepsize at end (linear descent)
:param start_vicinity: proportion of randomness of restart-location for gradient descent at beginning
:param end_vicinity: same at end (linear decay)
:param sim_seed: seed for simulation of process on fitted coefficients
:param verbose: verbosity, comments during fitting
:return: 'OperationNode' containing simulated garch(1,1) process on fitted coefficients & variances of simulated fitted process & constant term of fitted process & 1-st arch-coefficient of fitted process & 1-st garch-coefficient of fitted process & drawbacks: slow convergence of optimization (sort of simulated annealing/gradient descent)
"""
params_dict = {'X': X, 'kmax': kmax, 'momentum': momentum, 'start_stepsize': start_stepsize, 'end_stepsize': end_stepsize, 'start_vicinity': start_vicinity, 'end_vicinity': end_vicinity, 'sim_seed': sim_seed, 'verbose': verbose} | apache/incubator-systemml | [
948,
427,
948,
18,
1447142406
] |
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456') | quiltdata/quilt-compiler | [
1223,
86,
1223,
59,
1486694763
] |
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
)) | quiltdata/quilt-compiler | [
1223,
86,
1223,
59,
1486694763
] |
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called() | quiltdata/quilt-compiler | [
1223,
86,
1223,
59,
1486694763
] |
def __init__(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC | idaholab/raven | [
168,
104,
168,
215,
1490297367
] |
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs | idaholab/raven | [
168,
104,
168,
215,
1490297367
] |
def get_dpo_proto(addr):
if ip_address(addr).version == 6:
return DpoProto.DPO_PROTO_IP6
else:
return DpoProto.DPO_PROTO_IP4 | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def __init__(self, addr):
self.addr = addr
self.ip_addr = ip_address(text_type(self.addr)) | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def version(self):
return self.ip_addr.version | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def address(self):
return self.addr | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def length(self):
return self.ip_addr.max_prefixlen | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def bytes(self):
return self.ip_addr.packed | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def __ne__(self, other):
return not (self == other) | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def __init__(self, saddr, gaddr, glen):
self.saddr = saddr
self.gaddr = gaddr
self.glen = glen
if ip_address(self.saddr).version != \
ip_address(self.gaddr).version:
raise ValueError('Source and group addresses must be of the '
'same address family.') | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def length(self):
return self.glen | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def version(self):
return ip_address(self.gaddr).version | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def __eq__(self, other):
if isinstance(other, self.__class__):
return (self.glen == other.glen and
self.saddr == other.gaddr and
self.saddr == other.saddr)
elif (hasattr(other, "grp_address_length") and
hasattr(other, "grp_address") and
hasattr(other, "src_address")):
# vl_api_mprefix_t
if 4 == self.version:
return (self.glen == other.grp_address_length and
self.gaddr == str(other.grp_address.ip4) and
self.saddr == str(other.src_address.ip4))
else:
return (self.glen == other.grp_address_length and
self.gaddr == str(other.grp_address.ip6) and
self.saddr == str(other.src_address.ip6))
return NotImplemented | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def __init__(self, test, policer_index, is_ip6=False):
self._test = test
self._policer_index = policer_index
self._is_ip6 = is_ip6 | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def remove_vpp_config(self):
self._test.vapi.ip_punt_police(policer_index=self._policer_index,
is_ip6=self._is_ip6, is_add=False) | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def __init__(self, test, rx_index, tx_index, nh_addr):
self._test = test
self._rx_index = rx_index
self._tx_index = tx_index
self._nh_addr = ip_address(nh_addr) | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def add_vpp_config(self):
self._test.vapi.ip_punt_redirect(punt=self.encode(), is_add=True)
self._test.registry.register(self, self._test.logger) | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def get_vpp_config(self):
is_ipv6 = True if self._nh_addr.version == 6 else False
return self._test.vapi.ip_punt_redirect_dump(
sw_if_index=self._rx_index, is_ipv6=is_ipv6) | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def __init__(self, test, nh, pmtu, table_id=0):
self._test = test
self.nh = nh
self.pmtu = pmtu
self.table_id = table_id | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def modify(self, pmtu):
self.pmtu = pmtu
self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh,
'table_id': self.table_id,
'path_mtu': self.pmtu})
return self | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def query_vpp_config(self):
ds = list(self._test.vapi.vpp.details_iter(
self._test.vapi.ip_path_mtu_get))
for d in ds:
if self.nh == str(d.pmtu.nh) \
and self.table_id == d.pmtu.table_id \
and self.pmtu == d.pmtu.path_mtu:
return True
return False | FDio/vpp | [
923,
525,
923,
24,
1499444980
] |
def looks_like_hash(sha):
return bool(HASH_REGEX.match(sha)) | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_base_rev_args(rev):
return [rev] | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_git_version(self):
VERSION_PFX = 'git version '
version = self.run_command(
['version'], show_stdout=False, stdout_only=True
)
if version.startswith(VERSION_PFX):
version = version[len(VERSION_PFX):].split()[0]
else:
version = ''
# get first 3 positions of the git version because
# on windows it is x.y.z.windows.t, and this parses as
# LegacyVersion which always smaller than a Version.
version = '.'.join(version.split('.')[:3])
return parse_version(version) | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_current_branch(cls, location):
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
"""
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
# HEAD rather than a symbolic ref. In addition, the -q causes the
# command to exit with status code 1 instead of 128 in this case
# and to suppress the message to stderr.
args = ['symbolic-ref', '-q', 'HEAD']
output = cls.run_command(
args,
extra_ok_returncodes=(1, ),
show_stdout=False,
stdout_only=True,
cwd=location,
)
ref = output.strip()
if ref.startswith('refs/heads/'):
return ref[len('refs/heads/'):]
return None | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_revision_sha(cls, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev to pre-filter the list.
output = cls.run_command(
['show-ref', rev],
cwd=dest,
show_stdout=False,
stdout_only=True,
on_returncode='ignore',
)
refs = {}
for line in output.strip().splitlines():
try:
sha, ref = line.split()
except ValueError:
# Include the offending line to simplify troubleshooting if
# this error ever occurs.
raise ValueError('unexpected show-ref line: {!r}'.format(line))
refs[ref] = sha
branch_ref = 'refs/remotes/origin/{}'.format(rev)
tag_ref = 'refs/tags/{}'.format(rev)
sha = refs.get(branch_ref)
if sha is not None:
return (sha, True)
sha = refs.get(tag_ref)
return (sha, False) | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def _should_fetch(cls, dest, rev):
"""
Return true if rev is a ref or is a commit that we don't have locally.
Branches and tags are not considered in this method because they are
assumed to be always available locally (which is a normal outcome of
``git clone`` and ``git fetch --tags``).
"""
if rev.startswith("refs/"):
# Always fetch remote refs.
return True
if not looks_like_hash(rev):
# Git fetch would fail with abbreviated commits.
return False
if cls.has_commit(dest, rev):
# Don't fetch if we have the commit locally.
return False
return True | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def resolve_revision(cls, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> RevOptions
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
"""
rev = rev_options.arg_rev
# The arg_rev property's implementation for Git ensures that the
# rev return value is always non-None.
assert rev is not None
sha, is_branch = cls.get_revision_sha(dest, rev)
if sha is not None:
rev_options = rev_options.make_new(sha)
rev_options.branch_name = rev if is_branch else None
return rev_options
# Do not show a warning for the common case of something that has
# the form of a Git commit hash.
if not looks_like_hash(rev):
logger.warning(
"Did not find branch or tag '%s', assuming revision or ref.",
rev,
)
if not cls._should_fetch(dest, rev):
return rev_options
# fetch the requested revision
cls.run_command(
make_command('fetch', '-q', url, rev_options.to_args()),
cwd=dest,
)
# Change the revision to the SHA of the ref we fetched
sha = cls.get_revision(dest, rev='FETCH_HEAD')
rev_options = rev_options.make_new(sha)
return rev_options | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def is_commit_id_equal(cls, dest, name):
"""
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
"""
if not name:
# Then avoid an unnecessary subprocess call.
return False
return cls.get_revision(dest) == name | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def switch(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
self.run_command(
make_command('config', 'remote.origin.url', url),
cwd=dest,
)
cmd_args = make_command('checkout', '-q', rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
self.update_submodules(dest) | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_remote_url(cls, location):
"""
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
"""
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if there are no matching lines.
stdout = cls.run_command(
['config', '--get-regexp', r'remote\..*\.url'],
extra_ok_returncodes=(1, ),
show_stdout=False,
stdout_only=True,
cwd=location,
)
remotes = stdout.splitlines()
try:
found_remote = remotes[0]
except IndexError:
raise RemoteNotFoundError
for remote in remotes:
if remote.startswith('remote.origin.url '):
found_remote = remote
break
url = found_remote.split(' ')[1]
return url.strip() | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def has_commit(cls, location, rev):
"""
Check if rev is a commit that is available in the local repository.
"""
try:
cls.run_command(
['rev-parse', '-q', '--verify', "sha^" + rev],
cwd=location,
log_failed_cmd=False,
)
except InstallationError:
return False
else:
return True | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_revision(cls, location, rev=None):
if rev is None:
rev = 'HEAD'
current_rev = cls.run_command(
['rev-parse', rev],
show_stdout=False,
stdout_only=True,
cwd=location,
)
return current_rev.strip() | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_subdirectory(cls, location):
"""
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
"""
# find the repo root
git_dir = cls.run_command(
['rev-parse', '--git-dir'],
show_stdout=False,
stdout_only=True,
cwd=location,
).strip()
if not os.path.isabs(git_dir):
git_dir = os.path.join(location, git_dir)
repo_root = os.path.abspath(os.path.join(git_dir, '..'))
return find_path_to_setup_from_repo_root(location, repo_root) | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
"""
# Works around an apparent Git bug
# (see https://article.gmane.org/gmane.comp.version-control.git/146500)
scheme, netloc, path, query, fragment = urlsplit(url)
if scheme.endswith('file'):
initial_slashes = path[:-len(path.lstrip('/'))]
newpath = (
initial_slashes +
urllib_request.url2pathname(path)
.replace('\\', '/').lstrip('/')
)
after_plus = scheme.find('+') + 1
url = scheme[:after_plus] + urlunsplit(
(scheme[after_plus:], netloc, newpath, query, fragment),
)
if '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
url = url.replace('ssh://', '')
else:
url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
return url, rev, user_pass | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def update_submodules(cls, location):
if not os.path.exists(os.path.join(location, '.gitmodules')):
return
cls.run_command(
['submodule', 'update', '--init', '--recursive', '-q'],
cwd=location,
) | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def get_repository_root(cls, location):
loc = super(Git, cls).get_repository_root(location)
if loc:
return loc
try:
r = cls.run_command(
['rev-parse', '--show-toplevel'],
cwd=location,
show_stdout=False,
stdout_only=True,
on_returncode='raise',
log_failed_cmd=False,
)
except BadCommand:
logger.debug("could not determine if %s is under git control "
"because git is not available", location)
return None
except InstallationError:
return None
return os.path.normpath(r.rstrip('\r\n')) | pantsbuild/pex | [
2269,
235,
2269,
149,
1405962372
] |
def test_convert_yaml_to_json_string_returns_valid_json_string(self):
data = textwrap.dedent("""
foo:
foo: baa
""")
self.assertEqual('{\n "foo": {\n "foo": "baa"\n }\n}', util.convert_yaml_to_json_string(data)) | marco-hoyer/cfn-sphere | [
82,
26,
82,
4,
1438784024
] |
def test_convert_json_to_yaml_string_returns_valid_yaml_string(self):
data = textwrap.dedent("""
{
"foo": {
"foo": "baa"
}
}
""")
self.assertEqual('foo:\n foo: baa\n', util.convert_json_to_yaml_string(data)) | marco-hoyer/cfn-sphere | [
82,
26,
82,
4,
1438784024
] |
def test_get_cfn_api_server_time_returns_gmt_datetime(self, urlopen_mock):
urlopen_mock.return_value.info.return_value.get.return_value = "Mon, 21 Sep 2015 17:17:26 GMT"
expected_timestamp = datetime(year=2015, month=9, day=21, hour=17, minute=17, second=26, tzinfo=tzutc())
self.assertEqual(expected_timestamp, util.get_cfn_api_server_time()) | marco-hoyer/cfn-sphere | [
82,
26,
82,
4,
1438784024
] |
def test_get_cfn_api_server_time_raises_exception_on_empty_date_header(self, urlopen_mock):
urlopen_mock.return_value.info.return_value.get.return_value = ""
with self.assertRaises(CfnSphereException):
util.get_cfn_api_server_time() | marco-hoyer/cfn-sphere | [
82,
26,
82,
4,
1438784024
] |
def my_retried_method(count_func):
count_func()
exception = CfnSphereBotoError(
ClientError(error_response={"Error": {"Code": "Throttling", "Message": "Rate exceeded"}},
operation_name="DescribeStacks"))
raise exception | marco-hoyer/cfn-sphere | [
82,
26,
82,
4,
1438784024
] |
def test_with_boto_retry_does_not_retry_for_simple_exception(self):
count_func = Mock()
@util.with_boto_retry(max_retries=1, pause_time_multiplier=1)
def my_retried_method(count_func):
count_func()
raise Exception
with self.assertRaises(Exception):
my_retried_method(count_func)
self.assertEqual(1, count_func.call_count) | marco-hoyer/cfn-sphere | [
82,
26,
82,
4,
1438784024
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.