def post(self): """ Endpoint to create new project""" data = request.get_json() title = data.get('title') user = get_jwt_identity() project_exist = Project.find_by_title_and_user(title=title, user_id=user.get('id')) if project_exist: raise ValidationError( { "message": serialization_messages['exists'].format( 'Project with title') }, 409) data['createdBy'] = user.get("id") project = Project() user_list = assign_user(data.get('assignees')) convert_date_to_date_time(data['due_date']) data['assignees'] = user_list if user_list is not None else [] assignee_ids = data['assignees'] del data['assignees'] schema = ProjectSchema() project_data = schema.load_object_into_schema(data) project.created_by = data['createdBy'] project.title = data['title'] project.description = data['description'] project.due_date = data['due_date'] project.assignees = assignee_ids project.save() return response('success', message=success_messages['created'].format('Project'), data=schema.dump(project).data, status_code=201)
def setUp(self): """ Defining test client and other test variables """ self.project_name = "New Project 1" self.project_description = "Awesome Project" self.project = Project(name=self.project_name, description=self.project_description)
def test_update_project(self): Project.create(name='tomate', description='sdfgh sdfgjk', url='hallo') response = self.client.put('/tomate/', '{"description":"tomatensalat"}', **{'Authorization':'Bearer '+self.login.token()}) self.assertEqual(response.status_code, 200) project = Project.objects.get(name='tomate') self.assertEqual(project.description, 'tomatensalat') self.assertEqual(project.url, 'hallo')
def test_create_location(self): Project.create(name='tomate', description='tomatensalat', url='hallo') response = self.client.post('/tomate/locations/', {'title':'funfunfun', 'description':'nochmehrfun', 'lat':'0.0', 'lng':'0.0'}, **{'Authorization':'Bearer '+self.login.token()}) self.assertEqual(response.status_code, 201) location = Location.objects.get(title='funfunfun') self.assertEqual(location.title, 'funfunfun') self.assertEqual(location.description, 'nochmehrfun')
def delete(self, idProject): project = Project.getProject(idProject, current_user.id) if project != None: result = Project.delete_project(idProject) if result: return make_response( jsonify({'result': 'Projeto removido com sucesso!'}), 200) return make_response( jsonify({'error': 'Ocorreu um erro! Tente outra vez!'}), 500) return make_response(jsonify({'project': 'Projeto nao encontrado!'}), 404)
def import_projects(request): if request.method == 'POST': Project.objects.all().delete() req_body = request.FILES['file'].read() projects_dict = simplexml.loads(req_body)['projects'] for p in projects_dict: project_tosave = Project(name=p['name'], description=p['description']) project_tosave.save() return HttpResponse(status=200) return HttpResponse(status=400)
def add_project(self, name, mailing_list="", git_repo=""): p = Project(name=name, mailing_list=mailing_list, git=git_repo or self.create_git_repo(name)) p.save() push_repo = self.create_git_repo(name + "_push") p.set_property("git.push_to", push_repo) p.set_property("git.public_repo", push_repo) p.set_property("git.url_template", push_repo) return p
def put(self, idProject): data = request.get_json() project = Project.getProject(idProject, current_user.id) if project != None: result = Project.update_project(idProject, data) if result: return make_response( jsonify({'result': 'Projeto atualizado com sucesso!'}), 200) return make_response( jsonify({'error': 'Ocorreu um erro! Tente outra vez!'}), 500) return make_response(jsonify({'project': 'Projeto nao encontrado!'}), 404)
def post(self): data = json.loads(self.request.body) current_user = User.current_user() project = Project( name=data.get('name'), note=data.get('note')) project.put() collaborator = Collaborator( project=project, user=current_user, is_manager=True) collaborator.put() self.response.write(json.dumps(project.to_dict()))
def delete(self, task_id): """ Delete a single task :param task_id: :return: """ user = get_jwt_identity() task_exists = Task.find_by_id(task_id) if task_exists is None: raise ValidationError({'message': 'Task not found'}) Project.delete_item(task_exists) return {'status': 'success', 'message': 'Task deleted successfully'}
def post(self): data = request.get_json() project = Project.getProjectByName(data["name"], current_user.id) id = current_user.id if project == None: result = Project.add_project(current_user.id, data) if result: return make_response( jsonify({'result': 'Projeto criado com sucesso!'}), 201) return make_response( jsonify({'error': 'Ocorreu um erro! Tente outra vez!'}), 200) return make_response( jsonify({'name': 'Ja tem um nome de projeto igual a este!'}), 400)
def delete(self, project_id): """ Delete a single project :param project_id: :return: """ user = get_jwt_identity() project_exists = Project.find_by_id_and_user(project_id, user.get('id')) if project_exists is None: raise ValidationError({'message': 'Project thing not found'}) Project.delete_item(project_exists) return {'status': 'success', 'message': 'Project deleted successfully'}
def handle(self, *args, **kwargs): path = kwargs['path'] df = pd.read_csv(path) upper_range = len(df) print("Wait Data is being Loaded") try: proj = [ Project( name=(df['Project Name'][row]), code=df['Project Code'][row], investment_primary=df['Investment Focus (Primary)'][row], investment_secondary=df['Investment Focus (Additional)'][row], ) for row in range(0, upper_range) ] proj_data = Project.objects.bulk_create(proj) if proj_data: self.stdout.write('Successfully loaded Partner data ..') # for row in range(0, upper_range): # print(df['Partner Name'][row]) except Exception as e: print(e)
def test_resource_quick_create_with_details(self): project = Project.quick_create(title="TEST") extra_data = {"rate": 100} resource = Resource.quick_create(project=project, **extra_data) assert resource.project.title == 'TEST', 'Expect project is explicitly set' assert resource.rate == 100.00, 'Expect rate to be set by kwargs'
def put(self, project_id): data = json.loads(self.request.body) project = Project.get(project_id) project.name = data.get('name') project.note = data.get('note') project.put() self.response.write(json.dumps(project.to_dict()))
def test_get_location(self): project = Project.create(name='tomate', description='tomatensalat', url='hallo') Location.create(title='funfunfun', lat=0.0, lng=0.0, description='nochmehrfun', project=project) response = self.client.get('/tomate/funfunfun/', **{'Authorization':'Bearer '+self.login.token()}) self.assertEqual(response.status_code, 200) data = response.content.decode('utf-8') self.assertJSONEqual(data, {'title':'funfunfun', 'description':'nochmehrfun', 'lat':0.0, 'lng':0.0})
def add_project(self, name, mailing_list="", git_repo=""): p = Project( name=name, mailing_list=mailing_list, git=git_repo or self.create_git_repo(name), ) push_repo = self.create_git_repo(name + "_push") p.config = { "git": { "push_to": push_repo, "public_repo": push_repo, "url_template": push_repo, } } p.save() return p
def patch(self, task_id): """ Endpoint to update task""" request_data = request.get_json() user = get_jwt_identity() task = Task.get_or_404(task_id) schema = TaskSchema(context={'id': task_id}) if 'task_assignees' in request_data: project = Project.get_or_404(task.project_id) assignee_list = check_assignee(request_data.get('task_assignees'), project.assignees) if assignee_list is not None: user_list = assign_user(assignee_list) assignees = user_list if user_list is not None else [] del request_data['task_assignees'] data = schema.load_object_into_schema(request_data, partial=True) data['task_assignees'] = assignees task.update_(**data) else: data = schema.load_object_into_schema(request_data, partial=True) task.update_(**data) return response('success', message=success_messages['updated'].format('Task'), data=schema.dump(task).data, status_code=200)
def test_update_location(self): project = Project.create(name='tomate', description='tomatensalat', url='hallo') Location.create(title='funfunfun', lat=0.0, lng=0.0, description='nochmehrfun', project=project) response = self.client.put('/tomate/funfunfun/', '{"description":"wenigerfunohhhh"}', **{'Authorization':'Bearer '+self.login.token()}) self.assertEqual(response.status_code, 200) location = Location.objects.get(title='funfunfun') self.assertEqual(location.description, 'wenigerfunohhhh')
def test_delete_location(self): project = Project.create(name='tomate', description='tomatensalat', url='hallo') Location.create(title='funfunfun', lat=0.0, lng=0.0, description='nochmehrfun', project=project) response = self.client.delete('/tomate/funfunfun/', **{'Authorization':'Bearer '+self.login.token()}) self.assertEqual(response.status_code, 200) location = Location.objects.filter(title='funfunfun') self.assertEqual(len(location), 0)
def get(self, project_id): project = Project.get(project_id) collaborators = Collaborator.all()\ .filter('project =', project) content = json.dumps([ c.to_dict() for c in collaborators if c.project.deleted_at is None ]) self.response.write(content)
def _req_body_to_project(request): request_body_fields = request.body.decode('utf-8') project_fields = json.loads(request_body_fields) project = Project( name=project_fields['name'].encode('utf-8'), description=project_fields['description'].encode('utf-8'), ) return project
def test_delete_project_fail_by_user_with_read_scope_only(self): factory = APIRequestFactory() view = ProjectDetail.as_view() Project.objects.bulk_create([ Project(id=1, title='Test1', description='d1'), Project(id=2, title='Test2', description='d2'), Project(id=3, title='Test3', description='d3') ]) request = factory.delete('/api/projects/1') force_authenticate(request, user=self.test_user, token=self.read_access_token) response = view(request, pk='1') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def post(self, project_id): data = json.loads(self.request.body) project = Project.get(project_id) participant = Participant(name=data.get('name'), note=data.get('note'), project=project, json=DEFAULT_JSON) participant.put() self.response.write(json.dumps(participant.to_dict()))
def post(self, request): HasUser.load(self, request) Project(user=self.user, name=request.data['name'], description=request.data['description']).save() return Response(status=status.HTTP_200_OK)
def create_project( project: models.Project = Body(PROJECT_EXAMPLE, example=PROJECT_EXAMPLE) ): "Post a project catalog" _id = mauve_db.insert_collection(PJ_COLL_NAME, docs=project.dict()) mauve_db.update_collection( PJ_COLL_NAME, doc={"id": str(_id)}, filter_dict={"_id": _id} ) return {"id": str(_id)}
def create_employee_data(): user1 = User(email="*****@*****.**", password="******") db.session.add(user1) db.session.commit() project = Project(name="Proyecto A", last_name="Last Name") db.session.add(project) db.session.commit() return "Print employee data"
def test_delete_project(self): factory = APIRequestFactory() view = ProjectDetail.as_view() projects = Project.objects.bulk_create([ Project(id=1, title='Test1', description='d1'), Project(id=2, title='Test2', description='d2'), Project(id=3, title='Test3', description='d3') ]) project = projects[0] request = factory.delete('/api/projects/1') force_authenticate(request, user=self.test_user, token=self.full_access_token) response = view(request, pk='1') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(len(Project.objects.all()), 2) self.assertNotIn(project, Project.objects.all())
def test_project_user_unique_together(self): project = Project.quick_create() start_date = date.today() Resource.objects.create(project=project, user=1, start_date=start_date) Resource.objects.create(project=project, user=2, start_date=start_date) try: Resource.objects.create(project=project, user=2) self.fail( "Should not be able to add the same project and user twice") except IntegrityError: pass
class ModelTestCase(TestCase): """ This test case defines the test suite for project model. """ def setUp(self): """ Defining test client and other test variables """ self.project_name = "New Project 1" self.project_description = "Awesome Project" self.project = Project(name=self.project_name, description=self.project_description) def test_model_can_create_project(self): """ Test the project model can create a project """ old_count = Project.objects.count() self.project.save() new_count = Project.objects.count() self.assertNotEqual(old_count, new_count)
def restore_object(self, attrs, instance=None): if instance: return super(ProjectSerializer, self)\ .restore_object(attrs, instance) if 'request' in self.context: created_by = self.context['request'].user return Project( name=attrs.get('name'), organization=attrs.get('organization'), created_by=created_by, ) return attrs
def setUp(self): self.c = Client(Authorization='Token 123') self.joe_admin = User.objects.create_superuser(username="******", password="******", email="*****@*****.**") self.joe_soap = User.objects.create_user(username="******", password="******") self.joe_soap.save() ## setup a bunch of Projects p1 = Project.quick_create(title="P1", description="Search me", is_billable=True) p2 = Project.quick_create(title="P2", is_billable=True) p3 = Project.quick_create(title="P3", is_active=False) p4 = Project.quick_create(title="P4", user=self.joe_soap.pk) p5 = Project.quick_create(title="P5", user=self.joe_soap.pk) p6 = Project.quick_create(title="P6") Resource.quick_create(user=self.joe_soap.pk, project=p4) Resource.quick_create(user=self.joe_soap.pk, project=p3) Resource.quick_create(user=self.joe_admin.pk, project=p1) Resource.quick_create(user=self.joe_admin.pk, project=p2)
def import_projects(request): if request.method == 'POST': req_body = request.FILES['file'].read() projects_dict = simplexml.loads(req_body)['projects'] projects = [ Project(0, p['name'], p['description']) for p in projects_dict ] with connect() as conn: dbprojects = Projects(conn) dbprojects.importall(projects) return HttpResponse(status=200) return HttpResponse(status=400)
def get(self, project_id, participant_id=None): if participant_id: participant = Participant.get(participant_id) if participant.deleted_at is not None: self.error(404) self.response.write(json.dumps(participant.to_dict())) else: project = Project.get(project_id) participants = Participant.all()\ .filter('project =', project)\ .order('created_at') self.response.write(json.dumps([p.to_dict() for p in participants]))
def delete(self, idProject, idTask): project = Project.getProject(idProject, current_user.id) if project != None: task = Task.getTask(idProject, idTask) if task != None: result = Task.delete_task(idProject, idTask) if result: return make_response( jsonify({'result': 'Task removida com sucesso!'}), 200) return make_response( jsonify({'error': 'Ocorreu um erro! Tente de outra vez!'}), 500) return make_response(jsonify({'task': 'Task nao encontrada!'}), 404)
def post(self): """ Endpoint to create new Task""" data = request.get_json() title = data.get('title') formatted_date = convert_date_to_date_time(data['due_date']) schema = TaskSchema() project_id = data['projectId'] project = Project.get_or_404(project_id) task_exist = Task.find_by_title_and_project_id(title=title, project_id=project.id) if task_exist: raise ValidationError( { "message": serialization_messages['exists'].format('Task with title') }, 409) if not check_date_difference(formatted_date, project.due_date): raise ValidationError( { "message": "Tasks cannot be created under this project because of dat difference" }, 401) assignee_list = check_assignee(data.get('task_assignees'), project.assignees) if assignee_list is not None: user_list = assign_user(assignee_list) data['task_assignees'] = user_list else: data['task_assignees'] = [] assignee_ids = data['task_assignees'] if data[ 'task_assignees'] is not None else [] del data['task_assignees'] task_data = schema.load_object_into_schema(data) task = Task() task.title = data['title'] task.description = data['description'] task.due_date = data['due_date'] task.task_assignees = assignee_ids task.project_id = project.id task.save() task.save() return response('success', message=success_messages['created'].format('Task'), data=schema.dump(task).data, status_code=201)