Commit 12b2055a authored by Erlend Ydse's avatar Erlend Ydse
Browse files

Merge branch 'refactor-sonarqube' into 'master'

Refactor sonarqube

See merge request !6
parents eec1070f 73f1af52
Pipeline #128389 passed with stage
in 1 minute and 4 seconds
#import logging
import os
import dj_database_url
......@@ -25,34 +24,22 @@ def settings(config, *, db_colors=False, databases=True, test_runner=True, stati
if env.startswith('HEROKU_POSTGRESQL'):
db_color = env[len('HEROKU_POSTGRESQL_'):].split('_')[0]
#logger.info('Adding ${} to DATABASES Django setting ({}).'.format(env, db_color))
config['DATABASES'][db_color] = dj_database_url.parse(url, conn_max_age=conn_max_age, ssl_require=True)
if 'DATABASE_URL' in os.environ:
#logger.info('Adding $DATABASE_URL to default DATABASE Django setting.')
# Configure Django for DATABASE_URL environment variable.
config['DATABASES']['default'] = dj_database_url.config(conn_max_age=conn_max_age, ssl_require=True)
#logger.info('Adding $DATABASE_URL to TEST default DATABASE Django setting.')
# Enable test database if found in CI environment.
if 'CI' in os.environ:
config['DATABASES']['default']['TEST'] = config['DATABASES']['default']
#else:
#logger.info('$DATABASE_URL not found, falling back to previous settings!')
if test_runner:
if test_runner and 'CI' in os.environ:
# Enable test runner if found in CI environment.
if 'CI' in os.environ:
config['TEST_RUNNER'] = 'django_heroku.HerokuDiscoverRunner'
config['TEST_RUNNER'] = 'django_heroku.HerokuDiscoverRunner'
# Staticfiles configuration.
if staticfiles:
#logger.info('Applying Heroku Staticfiles configuration to Django settings.')
config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles')
config['STATIC_URL'] = '/static/'
......@@ -69,48 +56,9 @@ def settings(config, *, db_colors=False, databases=True, test_runner=True, stati
config['STATICFILES_STORAGE'] = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
if allowed_hosts:
#logger.info('Applying Heroku ALLOWED_HOSTS configuration to Django settings.')
config['ALLOWED_HOSTS'] = ['*']
"""
if logging:
logger.info('Applying Heroku logging configuration to Django settings.')
config['LOGGING'] = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' +
'pathname=%(pathname)s lineno=%(lineno)s ' +
'funcname=%(funcName)s %(message)s'),
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simple': {
'format': '%(levelname)s %(message)s'
}
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'testlogger': {
'handlers': ['console'],
'level': 'INFO',
}
}
}
"""
# SECRET_KEY configuration.
if secret_key:
if 'SECRET_KEY' in os.environ:
#logger.info('Adding $SECRET_KEY to SECRET_KEY Django setting.')
# Set the Django setting from the environment variable.
config['SECRET_KEY'] = os.environ['SECRET_KEY']
if secret_key and 'SECRET_KEY' in os.environ:
# Set the Django setting from the environment variable.
config['SECRET_KEY'] = os.environ['SECRET_KEY']
......@@ -6,12 +6,13 @@ from rest_framework.test import APIClient, APIRequestFactory, APITestCase
from workouts.models import Exercise
from sys import maxsize
from django.db.utils import IntegrityError
from PIL import Image
class WorkoutCreationTests(APITestCase):
def setUp(self):
self.path = "/api/workouts/"
self.client = APIClient()
now = timezone.now()
self.now = timezone.now()
self.registration_data = {
"username": "alice",
......@@ -44,7 +45,7 @@ class WorkoutCreationTests(APITestCase):
self.data = {
"name": "wBR",
"date": now,
"date": self.now,
"notes": "Good workout",
"visibility": "PR",
"exercise_instances": [self.exerciseA]}
......@@ -59,7 +60,7 @@ class WorkoutCreationTests(APITestCase):
self.data = {
"name": "wA",
"date": now,
"date": self.now,
"notes": "Good workout",
"visibility": "PU",
"exercise_instances": [self.exerciseA]}
......@@ -69,6 +70,12 @@ class WorkoutCreationTests(APITestCase):
self.access_token = response.data["access"]
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.access_token}")
def pretty_print_response(self, response):
if "status_code" in response.__dict__:
print(response.status_code)
if "data" in response.__dict__:
print(response.data)
### Black box FR5
def test_create_workout_normal_ok(self):
......@@ -202,3 +209,18 @@ class WorkoutCreationTests(APITestCase):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["count"], self.pu_workouts + 1)
# Regression tests
def test_create_workout_then_update(self):
data = {
"name": "wBF",
"date": self.now,
"notes": "Good workout",
"visibility": "PR",
"exercise_instances": [self.exerciseA],
"files": []}
response = self.client.post(self.path, data=data, format="json")
self.assertEqual(response.status_code, 201)
data["notes"] = "Bad workout"
response = self.client.put(f"{self.path}{response.data['id']}/", data=data, format="json")
self.assertEqual(response.status_code, 200)
\ No newline at end of file
......@@ -11,7 +11,6 @@ class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = get_user_model()
# list_display = UserAdmin.list_display + ('coach',)
fieldsets = UserAdmin.fieldsets + ((None, {"fields": ("coach",)}),)
add_fieldsets = UserAdmin.add_fieldsets + ((None, {"fields": ("coach",)}),)
......
......@@ -99,9 +99,8 @@ class UserPutSerializer(serializers.ModelSerializer):
instance.bio = validated_data["bio"]
if "profile_image" in validated_data:
instance.profile_image = validated_data["profile_image"]
if "symmetric_friends" in validated_data:
if len(validated_data["symmetric_friends"]) > 0:
instance.symmetric_friends.add(validated_data["symmetric_friends"][0])
if "symmetric_friends" in validated_data and len(validated_data["symmetric_friends"]) > 0:
instance.symmetric_friends.add(validated_data["symmetric_friends"][0])
return instance
......
......@@ -83,7 +83,6 @@ class UserDetail(
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
#self.serializer_class = UserPutSerializer
return self.partial_update(request, *args, **kwargs)
......@@ -103,7 +102,6 @@ class OfferList(
serializer.save(owner=self.request.user)
def get_queryset(self):
qs = Offer.objects.none()
result = Offer.objects.none()
if self.request.user:
......
......@@ -131,8 +131,16 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
instance.date = validated_data.get("date", instance.date)
instance.save()
# Handle ExerciseInstances
self.handle_exercise_instances(
instance=instance,
exercise_instances=exercise_instances,
exercise_instances_data=exercise_instances_data)
self.handle_workout_files(instance=instance, validated_data=validated_data)
return instance
def handle_exercise_instances(self, instance, exercise_instances, exercise_instances_data):
# This updates existing exercise instances without adding or deleting object.
# zip() will yield n 2-tuples, where n is
# min(len(exercise_instance), len(exercise_instance_data))
......@@ -161,9 +169,8 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
elif len(exercise_instances_data) < len(exercise_instances.all()):
for i in range(len(exercise_instances_data), len(exercise_instances.all())):
exercise_instances.all()[i].delete()
# Handle WorkoutFiles
def handle_workout_files(self, instance, validated_data):
if "files" in validated_data:
files_data = validated_data.pop("files")
files = instance.files
......@@ -184,8 +191,6 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
for i in range(len(files_data), len(files.all())):
files.all()[i].delete()
return instance
def get_owner_username(self, obj):
"""Returns the owning user's username
......
......@@ -71,10 +71,10 @@ class RememberMe(
return Response({"remember_me": self.rememberme()})
def post(self, request):
cookieObject = namedtuple("Cookies", request.COOKIES.keys())(
cookie_object = namedtuple("Cookies", request.COOKIES.keys())(
*request.COOKIES.values()
)
user = self.get_user(cookieObject)
user = self.get_user(cookie_object)
refresh = RefreshToken.for_user(user)
return Response(
{
......@@ -83,8 +83,8 @@ class RememberMe(
}
)
def get_user(self, cookieObject):
decode = base64.b64decode(cookieObject.remember_me)
def get_user(self, cookie_object):
decode = base64.b64decode(cookie_object.remember_me)
user, sign = pickle.loads(decode)
# Validate signature
......
......@@ -7,6 +7,14 @@ ARG DOMAIN
ARG URL_PREFIX
ARG PORT_PREFIX
# Install NodeJS
RUN apt-get update -y
RUN apt-get install -y curl
RUN curl -fsSL https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get install -y nodejs
RUN npm install npm@latest -g
RUN npm install -g cordova
# Set working dir
WORKDIR /app
......@@ -18,7 +26,7 @@ RUN echo "const HOST = '${URL_PREFIX}${DOMAIN}:${PORT_PREFIX}${GROUPID}';" > ./w
# Install cordova
# Also install shelljs because of windows for some reason
RUN apt-get update -y && apt-get install npm -y && npm install -g cordova && npm install shelljs
RUN apt-get update -y && npm install shelljs
# Run cordova app
CMD [ "cordova", "run", "browser", "--release", "--port=3000" ]
......@@ -89,7 +89,7 @@
</tbody>
</table>
<div id="bio-display" class="mt-1">
<h6><b>Bio:</b></h6>
<h6><strong>Bio:</strong></h6>
<p id="bio"></p>
<button type="button" class="btn btn-light" id="btn-bio-edit">
Edit
......@@ -97,7 +97,7 @@
</div>
<div id="bio-edit" class="hide mt-1">
<label for="textarea-bio-edit" class="form-label"
><b>Bio:</b></label
><strong>Bio:</strong></label
>
<textarea
id="textarea-bio-edit"
......
......@@ -11,21 +11,6 @@ async function fetchFriendRequests() {
}
}
// async function fetchFriends(id) {
// // Might just get from currentuser
// let response = await sendRequest("GET", `${HOST}/api/users/${id}/`);
// if (!response.ok) {
// throw new Error(`HTTP error! status: ${response.status}`);
// } else {
// let data = await response.json();
// let friends = data.results;
// return friends;
// }
// }
/**
*
* @param {String} username
......@@ -74,11 +59,6 @@ async function addFriend(url) {
}
}
// async function rejectFriend(id) {
// const currentUser = await getCurrentUser();
// console.log(`Removing friend ${id} from ${JSON.stringify(currentUser)}`);
// }
/**
*
* @param {{name: String, id: Number, date: Date}[]} friendRequests
......@@ -91,8 +71,6 @@ function renderFriendRequests(friendRequests) {
);
const cloneFriendRequest = templateFriendRequest.content.cloneNode(true);
// const divFriendRequest = cloneFriendRequest.querySelector("div.d-flex");
const h5 = cloneFriendRequest.querySelector("h5");
h5.textContent = friendRequest.name;
......@@ -182,9 +160,6 @@ async function searchFriends() {
}
window.addEventListener("DOMContentLoaded", async () => {
// const req = await fetchFriendRequests();
// console.log(req);
// renderFriendRequests(req);
const user = await getCurrentUser();
console.log(user)
await renderFriends(user.symmetric_friends);
......
......@@ -205,7 +205,6 @@ async function submitRoster() {
const form = new FormData();
form.append("status", "p");
form.append("recipient", athlete.url);
// let body = {'status': 'p', 'recipient': athlete.url};
let response = await sendRequest(
"POST",
`${HOST}/api/offers/`,
......
......@@ -52,13 +52,11 @@ async function displayOffers() {
let acceptButton = buttons[0];
let declineButton = buttons[1];
//acceptButton.id = `btn-accept-${offer.id}`;
acceptButton.addEventListener(
"click",
async (event) => await acceptOffer(event, offer.url, offer.owner)
);
//declineButton.id = `btn-decline-${offer.id}`;
declineButton.addEventListener(
"click",
async (event) => await declineOffer(event, offer.url)
......
......@@ -59,19 +59,7 @@ async function markViewedWorkout(workouts, currentUser) {
return
}
const lastWorkout = workouts.map(workout => workout.id).sort((a, b) => b - a)[0];
// const form = new FormData();
// form.append("last_seen_workout", lastWorkout)
// const response = await sendRequest("PATCH", `${HOST}/api/users/${currentUser.id}/`, form, "")
localStorage.setItem(`last_seen_workout_${currentUser.username}`, JSON.stringify(lastWorkout))
// if (response.ok) {
// const data = await response.json();
// console.log(`Updated last seen, data: ${JSON.stringify(data)}`)
// } else {
// const data = await response.json();
// const alert = createAlert("Could not add friend!", data);
// document.body.prepend(alert);
// }
}
window.addEventListener("DOMContentLoaded", async () => {
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment