public void Edit_4_CannotSaveACertificateWithInvalidFields()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            // obtains a valid certificate model
            ModelMedicalCertificateViewModel certificateModelFormModel = new ModelMedicalCertificateViewModel()
            {
                Name = "My Model",
                Text = "This is a reference: <%FIELD_1%>"
            };
            var mr = new MockRepository(true);
            var certificateModelTarget = mr.CreateController <ModelMedicalCertificatesController>();
            var certificateModelResult = certificateModelTarget.Edit(certificateModelFormModel);
            var modelId = this.db.ModelMedicalCertificates.First().Id;

            // tries to save
            MedicalCertificateViewModel formModel = new MedicalCertificateViewModel()
            {
                // both EXISTING
                ModelId   = modelId,
                PatientId = patientId
            };

            var target = mr.CreateController <MedicalCertificatesController>();
            var result = target.Edit(new[] { formModel });

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            Assert.AreEqual(false, target.ModelState.IsValid);
            Assert.AreEqual(1, target.ModelState.Count);
        }
        public void MedicalCertificateFieldsEditor_2_ModelIdIsSuppliedAndCertficateIdIsNot()
        {
            // create a model
            ModelMedicalCertificateViewModel formModel = new ModelMedicalCertificateViewModel()
            {
                Name = "My Model",
                Text = "This is a reference: <%PROP_1%>, <%pRoP_2%>, <%PrOP_3%>, <%ProP_4%>"
            };

            var mr = new MockRepository(true);
            var certificateModelcontroller = mr.CreateController <ModelMedicalCertificatesController>();

            certificateModelcontroller.Edit(formModel);
            var modelId = this.db.ModelMedicalCertificates.Select(m => m.Id).First();

            // create a certificate
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();

            var patientId        = this.db.Patients.First().Id;
            var controller       = mr.CreateController <MedicalCertificatesController>();
            var controllerResult = controller.MedicalCertificateFieldsEditor(modelId, null, null);

            // obtaining the view-model
            ViewResult view      = (ViewResult)controllerResult;
            var        viewModel = (MedicalCertificateViewModel)view.Model;

            Assert.AreEqual(4, viewModel.Fields.Count);
        }
        public void MedicalCertificateFieldsEditor_4_BothParametersAreSuppliedAndTheyDontMatch()
        {
            // create a model
            ModelMedicalCertificateViewModel certificateModelFormModel = new ModelMedicalCertificateViewModel()
            {
                Name = "My Model",
                Text = "This is a reference: <%PROP_1%>"
            };

            var mr = new MockRepository(true);
            var certificateModelcontroller = mr.CreateController <ModelMedicalCertificatesController>();

            certificateModelcontroller.Edit(certificateModelFormModel);
            var modelId = this.db.ModelMedicalCertificates.Select(m => m.Id).First();

            // create a certificate
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();

            var patientId = this.db.Patients.First().Id;

            var controller = mr.CreateController <MedicalCertificatesController>();
            MedicalCertificateViewModel formModel = new MedicalCertificateViewModel()
            {
                // both EXISTING
                ModelId   = modelId,
                PatientId = patientId,
                Fields    = new List <MedicalCertificateFieldViewModel>()
                {
                    new MedicalCertificateFieldViewModel()
                    {
                        Name = "prop_1", Value = "Este é o valor"
                    }
                }
            };

            // save the certificate
            controller.Edit(new[] { formModel });
            var certificateId = this.db.MedicalCertificates.Select(c => c.Id).First();

            // at this point we have 2 certificate models, "modelId" and "anotherModelId" and we have a certificate using "modelId". The point is
            // to call MedicalCertificateFieldsEditor passing "anotherModelId"

            var controllerResult = controller.MedicalCertificateFieldsEditor(modelId, certificateId, null);

            // obtaining the view-model
            ViewResult view      = (ViewResult)controllerResult;
            var        viewModel = (MedicalCertificateViewModel)view.Model;

            Assert.AreEqual(1, viewModel.Fields.Count);
            Assert.AreEqual("Este é o valor", viewModel.Fields[0].Value);
        }
        public void GetCertificateText_HappyPath()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();

            var patient     = this.db.Patients.First();
            var patientId   = patient.Id;
            var patientName = patient.Person.FullName;

            // obtains a valid certificate model
            ModelMedicalCertificateViewModel certificateModelFormModel = new ModelMedicalCertificateViewModel()
            {
                Name = "My Model",
                Text = "This is a reference: <%FIELD_1%>. This is the patient name: <%paCIENTE%>"
            };
            var mr = new MockRepository(true);
            var certificateModelController       = mr.CreateController <ModelMedicalCertificatesController>();
            var certificateModelControllerResult = certificateModelController.Edit(certificateModelFormModel);
            var modelId = this.db.ModelMedicalCertificates.First().Id;

            // tries to save
            MedicalCertificateViewModel formModel = new MedicalCertificateViewModel()
            {
                // both EXISTING
                ModelId   = modelId,
                PatientId = patientId,
                Fields    = new List <MedicalCertificateFieldViewModel>()
                {
                    new MedicalCertificateFieldViewModel()
                    {
                        Name = "field_1", Value = "This is a value"
                    }
                }
            };

            var certificateController       = mr.CreateController <MedicalCertificatesController>();
            var certificateControllerResult = certificateController.Edit(new[] { formModel });

            Assert.IsInstanceOfType(certificateControllerResult, typeof(ViewResult));
            Assert.AreEqual(true, certificateController.ModelState.IsValid);

            // Now verifies whether the result is the expected
            var newlyCreatedCertificate = this.db.MedicalCertificates.First();

            var certificateText = certificateController.GetCertificateText(newlyCreatedCertificate.Id);

            Assert.AreEqual("This is a reference: This is a value. This is the patient name: " + patientName, certificateText);
        }
        public void EditPost_UserIsOwner_WithInvalidData()
        {
            PracticeHomeController homeController;
            var mr = new MockRepository();
            try
            {
                mr.SetCurrentUser_Andre_CorrectPassword();
                mr.SetRouteData_ConsultorioDrHouse_GregoryHouse(typeof(PracticeHomeController), "Edit");

                homeController = mr.CreateController<PracticeHomeController>(callOnActionExecuting: false);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            var viewModel = new PracticeHomeControllerViewModel
            {
                PracticeName = "", // Cannot set practice name to empty
                PracticeTimeZone = 3
            };

            Mvc3TestHelper.SetModelStateErrors(homeController, viewModel);

            // Execute test: owner must have access to this view.
            var actionResult = Mvc3TestHelper.RunOnAuthorization(homeController, "Edit", "POST")
                            ?? Mvc3TestHelper.RunOnActionExecuting(homeController, "Edit", "POST")
                            ?? homeController.Edit(viewModel);

            // Asserts
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            Assert.AreEqual(null, ((ViewResult)actionResult).View);
        }
        public void EditPost_UserIsAdministrator()
        {
            PracticeHomeController homeController;
            var mr = new MockRepository();
            try
            {
                mr.SetCurrentUser_Miguel_CorrectPassword();
                mr.SetRouteData_ConsultorioDrHouse_GregoryHouse(typeof(PracticeHomeController), "Edit");

                homeController = mr.CreateController<PracticeHomeController>(callOnActionExecuting: false);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Execute test: owner must have access to this view.
            var actionResult = Mvc3TestHelper.RunOnAuthorization(homeController, "Edit", "POST")
                            ?? Mvc3TestHelper.RunOnActionExecuting(homeController, "Edit", "POST")
                            ?? homeController.Edit(new PracticeHomeControllerViewModel
                            {
                                PracticeName = "My New Practice Name",
                                PracticeTimeZone = 3
                            });

            // Asserts
            Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));
            var redirectResult = (RedirectToRouteResult)actionResult;
            Assert.AreEqual(2, redirectResult.RouteValues.Count);
            Assert.AreEqual("practicehome", string.Format("{0}", redirectResult.RouteValues["controller"]), ignoreCase: true);
            Assert.AreEqual("Index", string.Format("{0}", redirectResult.RouteValues["action"]), ignoreCase: true);
        }
        public void Edit_3_CannotSaveWithInvalidModelIdAndId()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            // tries to save
            var formModel = new MedicalCertificateViewModel()
            {
                // both EXISTING
                ModelId   = null,
                Id        = null,
                PatientId = patientId,
                Fields    = new List <MedicalCertificateFieldViewModel>()
                {
                    new MedicalCertificateFieldViewModel()
                    {
                        Name = "field_1"
                    },
                    new MedicalCertificateFieldViewModel()
                    {
                        Name = "field_2"
                    }
                }
            };

            var mr               = new MockRepository(true);
            var controller       = mr.CreateController <MedicalCertificatesController>();
            var controllerResult = controller.Edit(new[] { formModel });

            Assert.IsInstanceOfType(controllerResult, typeof(ViewResult));
            Assert.AreEqual(false, controller.ModelState.IsValid);
            Assert.AreEqual(1, controller.ModelState.Count);
        }
        public void Index_UserIsSecretary()
        {
            PracticeHomeController homeController;
            var mr = new MockRepository();

            try
            {
                var milena = Firestarter.CreateSecretary_Milena(this.db, this.db.Practices.First());
                mr.SetCurrentUser(milena.Users.Single(), "milena");
                mr.SetRouteData("Index", "practicehome", "App", "consultoriodrhouse");

                homeController = mr.CreateController <PracticeHomeController>(callOnActionExecuting: false);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Execute test: owner must have access to this view.
            var actionResult = Mvc3TestHelper.RunOnAuthorization(homeController, "Index")
                               ?? Mvc3TestHelper.RunOnActionExecuting(homeController, "Index")
                               ?? homeController.Index();

            // Asserts
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            Assert.AreEqual(null, ((ViewResult)actionResult).View);
        }
        public void Index_UserIsAdministrator()
        {
            PracticeHomeController homeController;
            var mr = new MockRepository();

            try
            {
                mr.SetCurrentUser_Miguel_CorrectPassword();
                mr.SetRouteData_ConsultorioDrHouse_GregoryHouse(typeof(PracticeHomeController), "Index");

                homeController = mr.CreateController <PracticeHomeController>(callOnActionExecuting: false);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Execute test: owner must have access to this view.
            var actionResult = Mvc3TestHelper.RunOnAuthorization(homeController, "Index")
                               ?? Mvc3TestHelper.RunOnActionExecuting(homeController, "Index")
                               ?? homeController.Index();

            // Asserts
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            Assert.AreEqual(null, ((ViewResult)actionResult).View);
        }
        public void EditPost_UserIsSecretary()
        {
            PracticeHomeController homeController;
            var mr = new MockRepository();

            try
            {
                var milena = Firestarter.CreateSecretary_Milena(this.db, this.db.Practices.First());
                mr.SetCurrentUser(milena.Users.Single(), "milena");
                mr.SetRouteData("Edit", "practicehome", "App", "consultoriodrhouse");

                homeController = mr.CreateController <PracticeHomeController>(callOnActionExecuting: false);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Execute test: owner must have access to this view.
            var actionResult = Mvc3TestHelper.RunOnAuthorization(homeController, "Edit", "POST")
                               ?? Mvc3TestHelper.RunOnActionExecuting(homeController, "Edit", "POST")
                               ?? homeController.Edit(new PracticeHomeControllerViewModel
            {
                PracticeName     = "My New Practice Name",
                PracticeTimeZone = 3
            });

            // Asserts
            Assert.IsInstanceOfType(actionResult, typeof(UnauthorizedResult));
        }
        public void EditPost_UserIsAdministrator()
        {
            PracticeHomeController homeController;
            var mr = new MockRepository();

            try
            {
                mr.SetCurrentUser_Miguel_CorrectPassword();
                mr.SetRouteData_ConsultorioDrHouse_GregoryHouse(typeof(PracticeHomeController), "Edit");

                homeController = mr.CreateController <PracticeHomeController>(callOnActionExecuting: false);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Execute test: owner must have access to this view.
            var actionResult = Mvc3TestHelper.RunOnAuthorization(homeController, "Edit", "POST")
                               ?? Mvc3TestHelper.RunOnActionExecuting(homeController, "Edit", "POST")
                               ?? homeController.Edit(new PracticeHomeControllerViewModel
            {
                PracticeName     = "My New Practice Name",
                PracticeTimeZone = 3
            });

            // Asserts
            Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));
            var redirectResult = (RedirectToRouteResult)actionResult;

            Assert.AreEqual(2, redirectResult.RouteValues.Count);
            Assert.AreEqual("practicehome", string.Format("{0}", redirectResult.RouteValues["controller"]), ignoreCase: true);
            Assert.AreEqual("Index", string.Format("{0}", redirectResult.RouteValues["action"]), ignoreCase: true);
        }
        public void EditPost_UserIsOwner_WithInvalidData()
        {
            PracticeHomeController homeController;
            var mr = new MockRepository();

            try
            {
                mr.SetCurrentUser_Andre_CorrectPassword();
                mr.SetRouteData_ConsultorioDrHouse_GregoryHouse(typeof(PracticeHomeController), "Edit");

                homeController = mr.CreateController <PracticeHomeController>(callOnActionExecuting: false);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            var viewModel = new PracticeHomeControllerViewModel
            {
                PracticeName     = "", // Cannot set practice name to empty
                PracticeTimeZone = 3
            };

            Mvc3TestHelper.SetModelStateErrors(homeController, viewModel);

            // Execute test: owner must have access to this view.
            var actionResult = Mvc3TestHelper.RunOnAuthorization(homeController, "Edit", "POST")
                               ?? Mvc3TestHelper.RunOnActionExecuting(homeController, "Edit", "POST")
                               ?? homeController.Edit(viewModel);

            // Asserts
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            Assert.AreEqual(null, ((ViewResult)actionResult).View);
        }
        public void Delete_HappyPath()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db, 1);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            var formModel = new DiagnosisViewModel
            {
                PatientId = patientId,
                Text      = "This is my diagnosis",
                Cid10Code = "Q878",
                Cid10Name = "Doença X"
            };

            var mr         = new MockRepository(true);
            var controller = mr.CreateController <DiagnosisController>();

            controller.Create(new[] { formModel });

            Assert.IsTrue(controller.ModelState.IsValid);

            // get's the newly created diagnosis
            var newlyCreatedDiagnosis = this.db.Diagnoses.First();

            // tries to delete the anamnese
            var result        = controller.Delete(newlyCreatedDiagnosis.Id);
            var deleteMessage = (JsonDeleteMessage)result.Data;

            Assert.AreEqual(true, deleteMessage.success);
            Assert.AreEqual(0, this.db.Anamnese.Count());
        }
예제 #14
0
        public void Edit_PassingInInvalidLaboratory()
        {
            MedicinesController controller;

            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController <MedicinesController>();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            var medicineName = "My Medicine";

            controller.Create(
                new MedicineViewModel()
            {
                Name = medicineName,
                // INVALID LAB
                LaboratoryId = 98
            });

            Assert.IsFalse(controller.ModelState.IsValid);
            Assert.AreEqual(1, controller.ModelState["LaboratoryId"].Errors.Count);
        }
        public void Delete_HappyPath()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            var formModel = new AnamneseViewModel()
            {
                PatientId = patientId,
                Conclusion = "This is my anamnese",
                DiagnosticHypotheses = new List<DiagnosticHypothesisViewModel>() {
                        new DiagnosticHypothesisViewModel() { Text = "Text", Cid10Code = "Q878" },
                        new DiagnosticHypothesisViewModel() { Text = "Text2", Cid10Code = "Q879" }
                   }
            };

            var mr = new MockRepository(true);
            var controller = mr.CreateController<AnamnesesController>();
            controller.Create(new[] { formModel });

            Assert.IsTrue(controller.ModelState.IsValid);

            // get's the newly created anamnese
            var newlyCreatedAnamnese = this.db.Anamnese.First();

            // tries to delete the anamnese
            var result = controller.Delete(newlyCreatedAnamnese.Id);
            JsonDeleteMessage deleteMessage = (JsonDeleteMessage)result.Data;

            Assert.AreEqual(true, deleteMessage.success);
            Assert.AreEqual(0, this.db.Anamnese.Count());
        }
예제 #16
0
        public void Edit_MinimalInformation_HappyPath()
        {
            MedicinesController controller;

            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController <MedicinesController>();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            var medicineName = "My Medicine";

            controller.Create(
                new MedicineViewModel()
            {
                Name = medicineName
            });

            var medicine = this.db.Medicines.FirstOrDefault(m => m.Name == medicineName);

            Assert.IsNotNull(medicine);
        }
        public void Delete_HappyPath()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db, 1);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            var formModel = new DiagnosisViewModel
                                {
                                    PatientId = patientId,
                                    Text = "This is my diagnosis",
                                    Cid10Code = "Q878",
                                    Cid10Name = "Doença X"
                                };

            var mr = new MockRepository(true);
            var controller = mr.CreateController<DiagnosisController>();
            controller.Create(new[] { formModel });

            Assert.IsTrue(controller.ModelState.IsValid);

            // get's the newly created diagnosis
            var newlyCreatedDiagnosis = this.db.Diagnoses.First();

            // tries to delete the anamnese
            var result = controller.Delete(newlyCreatedDiagnosis.Id);
            var deleteMessage = (JsonDeleteMessage)result.Data;

            Assert.AreEqual(true, deleteMessage.success);
            Assert.AreEqual(0, this.db.Anamnese.Count());
        }
예제 #18
0
        public void Delete_WhenTheresNoAssociation()
        {
            PatientsController controller;
            int     patientId;
            Patient patient;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr     = new MockRepository(true);
                controller = mr.CreateController <PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);
                patientId = patient.Id;
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patientId);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patientId);
            Assert.IsNull(patient);
        }
        public void Edit_HappyPath()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db, 1);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            var formModel = new DiagnosisViewModel
            {
                PatientId = patientId,
                Cid10Code = "CodeX",
                Cid10Name = "XDesease",
                Text      = "Notes"
            };

            var mr         = new MockRepository(true);
            var controller = mr.CreateController <DiagnosisController>();

            var referenceTime = DateTime.UtcNow;

            controller.UtcNowGetter = () => referenceTime;

            controller.Edit(new[] { formModel });

            Assert.IsTrue(controller.ModelState.IsValid);

            var diagnosis = this.db.Diagnoses.First();

            Assert.AreEqual(0, (referenceTime.Ticks - diagnosis.CreatedOn.Ticks) / 100000);
            Assert.AreEqual(patientId, diagnosis.PatientId);
            Assert.AreEqual(formModel.Text, diagnosis.Observations);
            Assert.AreEqual(formModel.Cid10Code, diagnosis.Cid10Code);
            Assert.AreEqual(formModel.Cid10Name, diagnosis.Cid10Name);
        }
예제 #20
0
        public void Search_ShouldRespectTheSearchTermWhenItsPresent()
        {
            PatientsController controller = null;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr     = new MockRepository(true);
                controller = mr.CreateController <PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 200);
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
            }

            var searchTerm            = "an";
            var matchingPatientsCount = this.db.Patients.Count(p => p.Person.FullName.Contains(searchTerm));

            // making an empty search
            var result = controller.Search(new Areas.App.Models.SearchModel()
            {
                Term = searchTerm,
                Page = 1
            });

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            var resultAsView = result as ViewResult;

            Assert.IsInstanceOfType(resultAsView.Model, typeof(SearchViewModel <PatientViewModel>));
            var model = resultAsView.Model as SearchViewModel <PatientViewModel>;

            Assert.AreEqual(matchingPatientsCount, model.Count);
            Assert.IsTrue(model.Objects.Count >= Code.Constants.GRID_PAGE_SIZE);
        }
        public void Delete_HappyPath()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            // obtains a valid certificate model
            ModelMedicalCertificateViewModel certificateModelFormModel = new ModelMedicalCertificateViewModel()
            {
                Name = "My Model",
                Text = "This is a reference: <%FIELD_1%>"
            };

            var mr = new MockRepository(true);
            var certificateModelController       = mr.CreateController <ModelMedicalCertificatesController>();
            var certificateModelControllerResult = certificateModelController.Edit(certificateModelFormModel);
            var certificateModel = this.db.ModelMedicalCertificates.First();

            // tries to save a certificate based on that model
            MedicalCertificateViewModel formModel = new MedicalCertificateViewModel()
            {
                ModelId   = certificateModel.Id,
                PatientId = patientId,
                Fields    = new List <MedicalCertificateFieldViewModel>()
                {
                    new MedicalCertificateFieldViewModel()
                    {
                        Name = "field_1", Value = "value 1"
                    }
                }
            };

            var certificateController       = mr.CreateController <MedicalCertificatesController>();
            var certificateControllerResult = certificateController.Edit(new[] { formModel });
            var certificate = this.db.MedicalCertificates.First();

            // tries to delete the certificate
            var result = certificateController.Delete(certificate.Id);
            JsonDeleteMessage deleteMessage = (JsonDeleteMessage)result.Data;

            Assert.AreEqual(true, deleteMessage.success, "deleteMessage.success must be true");
            Assert.AreEqual(0, this.db.MedicalCertificates.Count());
        }
예제 #22
0
        public void Edit_UpdatingExistingLeaflets()
        {
            MedicinesController controller;

            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController <MedicinesController>();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            var medicineName = "My Medicine";

            // all these active ingredients have already been created.
            // now we have to associate them with the original active ingredients

            var formModel = new MedicineViewModel()
            {
                Name     = medicineName,
                Leaflets = new List <MedicineLeafletViewModel>()
                {
                    new MedicineLeafletViewModel()
                    {
                        Url         = "http://www.google.com",
                        Description = "desc 1"
                    }
                }
            };

            controller.Create(formModel);

            var medicine = this.db.Medicines.FirstOrDefault(m => m.Name == medicineName);

            Assert.IsNotNull(medicine);
            Assert.AreEqual(1, medicine.Leaflets.Count);

            formModel.Id                      = medicine.Id;
            formModel.Leaflets[0].Id          = medicine.Leaflets.ElementAt(0).Id;
            formModel.Leaflets[0].Url         = "http://www.facebook.com";
            formModel.Leaflets[0].Description = "desc 2";

            // Let's edit now and change some properties
            controller.Edit(formModel);

            // we need to refresh since the DB inside the controller is different from this
            this.db.Refresh(RefreshMode.StoreWins, medicine.Leaflets);

            // verify that all the active ingredients inside the medicine are those that
            // we've EDITED here
            Assert.AreEqual(formModel.Leaflets[0].Url, medicine.Leaflets.ElementAt(0).Url);
            Assert.AreEqual(formModel.Leaflets[0].Description, medicine.Leaflets.ElementAt(0).Description);
        }
        public void Delete_HappyPath()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            // obtains a valid certificate model
            ModelMedicalCertificateViewModel certificateModelFormModel = new ModelMedicalCertificateViewModel()
            {
                Name = "My Model",
                Text = "This is a reference: <%FIELD_1%>"
            };

            var mr = new MockRepository(true);
            var certificateModelController = mr.CreateController<ModelMedicalCertificatesController>();
            var certificateModelControllerResult = certificateModelController.Edit(certificateModelFormModel);
            var certificateModel = this.db.ModelMedicalCertificates.First();

            // tries to save a certificate based on that model
            MedicalCertificateViewModel formModel = new MedicalCertificateViewModel()
            {
                ModelId = certificateModel.Id,
                PatientId = patientId,
                Fields = new List<MedicalCertificateFieldViewModel>()
                {
                     new MedicalCertificateFieldViewModel() { Name = "field_1", Value = "value 1" }
                }
            };

            var certificateController = mr.CreateController<MedicalCertificatesController>();
            var certificateControllerResult = certificateController.Edit(new[] { formModel });
            var certificate = this.db.MedicalCertificates.First();

            // tries to delete the certificate
            var result = certificateController.Delete(certificate.Id);
            JsonDeleteMessage deleteMessage = (JsonDeleteMessage)result.Data;

            Assert.AreEqual(true, deleteMessage.success, "deleteMessage.success must be true");
            Assert.AreEqual(0, this.db.MedicalCertificates.Count());
        }
        public void Delete_ShouldReturnProperResultWhenNotExisting()
        {
            var mr = new MockRepository(true);
            var controller = mr.CreateController<AnamnesesController>();

            // tries to delete the anamnese
            var result = controller.Delete(999);
            JsonDeleteMessage deleteMessage = (JsonDeleteMessage)result.Data;

            Assert.AreEqual(false, deleteMessage.success);
            Assert.IsNotNull(deleteMessage.text);
        }
        public void Create_1_HappyPath()
        {
            ExamsController controller;
            Patient         patient;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();
                var mr = new MockRepository(true);
                controller = mr.CreateController <ExamsController>();
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request.
            ActionResult actionResult;

            {
                var medicalProc = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.03.04.36-1");
                var viewModel   = new ExaminationRequestViewModel
                {
                    PatientId            = patient.Id,
                    Notes                = "Any text",
                    MedicalProcedureId   = medicalProc.Id,
                    MedicalProcedureName = "Hemograma com contagem de plaquetas ou frações (eritrograma, leucograma, plaquetas)",
                };

                actionResult = controller.Create(new[] { viewModel });
            }

            // Verifying the ActionResult.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");

            // Verifying the controller model-state.
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");

            // Verifying the database.
            Assert.IsTrue(this.db.ExaminationRequests.Any(x => x.PatientId == patient.Id), "Database record was not saved.");

            // Verifying the database.
            using (var db2 = DbTestBase.CreateNewCerebelloEntities())
            {
                var obj = db2.ExaminationRequests.FirstOrDefault(x => x.PatientId == patient.Id);
                Assert.IsNotNull(obj, "Database record was not saved.");
                Assert.AreEqual("Any text", obj.Text);
                Assert.AreEqual("4.03.04.36-1", obj.MedicalProcedureCode);
                Assert.AreEqual("Hemograma com contagem de plaquetas ou frações (eritrograma, leucograma, plaquetas)", obj.MedicalProcedureName);
            }
        }
        public void Create_WithoutMedicalProcedure()
        {
            ExamsController controller;
            Patient         patient;
            bool            isDbChangesSaved = false;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();
                var mr = new MockRepository(true);
                controller = mr.CreateController <ExamsController>(
                    setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request without the text.
            // This is not allowed and must generate a model state validation message.
            ActionResult actionResult;
            ExaminationRequestViewModel viewModel;

            {
                viewModel = new ExaminationRequestViewModel
                {
                    PatientId = patient.Id,
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);

                actionResult = controller.Create(new[] { viewModel });
            }

            // Verifying the ActionResult, and the DB.
            // - The result must be a ViewResult, with the name "Edit".
            // - The controller ModelState must have one validation message.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            var viewResult = (ViewResult)actionResult;

            Assert.AreEqual("edit", viewResult.ViewName, ignoreCase: true);
            Assert.IsFalse(controller.ModelState.IsValid, "ModelState should not be valid.");
            Assert.AreEqual(
                1,
                controller.ModelState.GetPropertyErrors(() => viewModel.MedicalProcedureName).Count(),
                "ModelState should contain one validation message.");

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }
예제 #27
0
        public void Edit_AddingNewLeaflet()
        {
            MedicinesController controller;

            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController <MedicinesController>();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            var medicineName = "My Medicine";

            // all these active ingredients have already been created.
            // now we have to associate them with the original active ingredients

            var formModel = new MedicineViewModel()
            {
                Name     = medicineName,
                Leaflets = new List <MedicineLeafletViewModel>()
                {
                    new MedicineLeafletViewModel()
                    {
                        Url         = "http:\\www.google.com",
                        Description = "desc 1"
                    },
                    new MedicineLeafletViewModel()
                    {
                        Url         = "http:\\www.google.com",
                        Description = "desc 2"
                    }
                }
            };

            controller.Create(formModel);


            var medicine = this.db.Medicines.FirstOrDefault(m => m.Name == medicineName);

            Assert.IsNotNull(medicine);
            Assert.AreEqual(2, medicine.Leaflets.Count);

            // verify that all the active ingredients inside the medicine are those that
            // we've created here
            Assert.AreEqual(formModel.Leaflets[0].Url, medicine.Leaflets.ElementAt(0).Url);
            Assert.AreEqual(formModel.Leaflets[0].Description, medicine.Leaflets.ElementAt(0).Description);
            Assert.AreEqual(formModel.Leaflets[1].Url, medicine.Leaflets.ElementAt(1).Url);
            Assert.AreEqual(formModel.Leaflets[1].Description, medicine.Leaflets.ElementAt(1).Description);
        }
        public void Delete_ShouldReturnProperResultWhenNotExisting()
        {
            var mr         = new MockRepository(true);
            var controller = mr.CreateController <DiagnosisController>();

            // tries to delete the anamnese
            var result        = controller.Delete(999);
            var deleteMessage = (JsonDeleteMessage)result.Data;

            Assert.AreEqual(false, deleteMessage.success);
            Assert.IsNotNull(deleteMessage.text);
        }
        public void CreateView_ViewNewAndFindNextAvailableTimeSlot_30DaysAfter_HappyPath()
        {
            ScheduleController controller;
            bool isDbChanged = false;

            // Dates that will be used by this test.
            // - utcNow and localNow: used to mock Now values from Utc and User point of view.
            // - start and end: start and end time of the appointments that will be created.
            var localNow = new DateTime(2012, 07, 25, 12, 00, 00, 000);

            try
            {
                // Creating DB entries.
                var docAndre = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                Firestarter.SetupDoctor(docAndre, this.db);

                var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(docAndre.Users.Single().Practice.WindowsTimeZoneId);
                DateTime utcNow = TimeZoneInfo.ConvertTimeToUtc(localNow, timeZoneInfo);

                var mr = new MockRepository(true);
                mr.SetRouteData_ConsultorioDrHouse_GregoryHouse(typeof(ScheduleController), "Create");
                controller = mr.CreateController<ScheduleController>(
                    setupNewDb: db2 => db2.SavingChanges += (s, e) => { isDbChanged = true; });
                controller.UtcNowGetter = () => utcNow;
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // View new appointment.
            // This must be ok, no exceptions, no validation errors.
            ActionResult actionResult;

            {
                actionResult = controller.Create(localNow.AddDays(30).Date, "", "", null, true);
            }

            // Verifying the ActionResult, and the DB.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");

            // Verify view-model.
            var viewResult = (ViewResult)actionResult;
            var viewModel = (AppointmentViewModel)viewResult.Model;
            Assert.AreEqual(new DateTime(2012, 08, 24), viewModel.LocalDateTime);
            Assert.AreEqual("09:00", viewModel.Start);
            Assert.AreEqual("09:30", viewModel.End);

            Assert.AreEqual(controller.ViewBag.IsEditingOrCreating, 'C');
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");
            Assert.IsFalse(isDbChanged, "View actions cannot change DB.");
        }
예제 #30
0
        public void Delete_WhenTheresAnExamResult()
        {
            PatientsController controller;
            int     patientId;
            Patient patient;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr     = new MockRepository(true);
                controller = mr.CreateController <PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);

                patientId = patient.Id;

                var examResult = new ExaminationResult()
                {
                    MedicalProcedureCode = "mcode",
                    MedicalProcedureName = "mname",
                    PatientId            = patientId,
                    CreatedOn            = DateTime.UtcNow,
                    Text       = "tudo deu certo",
                    PracticeId = doctor.PracticeId,
                };

                this.db.SYS_MedicalProcedure.AddObject(
                    new SYS_MedicalProcedure()
                {
                    Code = "mcode",
                    Name = "mname"
                });

                this.db.ExaminationResults.AddObject(examResult);

                this.db.SaveChanges();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patientId);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patientId);
            Assert.IsNull(patient);
        }
예제 #31
0
        public void Create_1_HappyPath()
        {
            ExamsController controller;
            Patient patient;
            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();
                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>();
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request.
            ActionResult actionResult;

            {
                var medicalProc = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.03.04.36-1");
                var viewModel = new ExaminationRequestViewModel
                {
                    PatientId = patient.Id,
                    Notes = "Any text",
                    MedicalProcedureId = medicalProc.Id,
                    MedicalProcedureName = "Hemograma com contagem de plaquetas ou frações (eritrograma, leucograma, plaquetas)",
                };

                actionResult = controller.Create(new[] { viewModel });
            }

            // Verifying the ActionResult.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");

            // Verifying the controller model-state.
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");

            // Verifying the database.
            Assert.IsTrue(this.db.ExaminationRequests.Any(x => x.PatientId == patient.Id), "Database record was not saved.");

            // Verifying the database.
            using (var db2 = DbTestBase.CreateNewCerebelloEntities())
            {
                var obj = db2.ExaminationRequests.FirstOrDefault(x => x.PatientId == patient.Id);
                Assert.IsNotNull(obj, "Database record was not saved.");
                Assert.AreEqual("Any text", obj.Text);
                Assert.AreEqual("4.03.04.36-1", obj.MedicalProcedureCode);
                Assert.AreEqual("Hemograma com contagem de plaquetas ou frações (eritrograma, leucograma, plaquetas)", obj.MedicalProcedureName);
            }
        }
        public void Edit_HappyPath()
        {
            // obtains a valid patient
            Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db);
            this.db.SaveChanges();
            var patientId = this.db.Patients.First().Id;

            // obtains a valid certificate model
            var certificateModelFormModel = new ModelMedicalCertificateViewModel()
            {
                Name = "My Model",
                Text = "This is a reference: <%FIELD_1%>"
            };
            var mr = new MockRepository(true);
            var certificateModelTarget = mr.CreateController <ModelMedicalCertificatesController>();
            var certificateModelResult = certificateModelTarget.Edit(certificateModelFormModel);
            var modelId = this.db.ModelMedicalCertificates.First().Id;

            // tries to save
            MedicalCertificateViewModel formModel = new MedicalCertificateViewModel()
            {
                // both EXISTING
                ModelId   = modelId,
                PatientId = patientId,
                Fields    = new List <MedicalCertificateFieldViewModel>()
                {
                    new MedicalCertificateFieldViewModel()
                    {
                        Name = "field_1", Value = "Este é o valor"
                    }
                }
            };

            var target = mr.CreateController <MedicalCertificatesController>();
            var result = target.Edit(new[] { formModel });

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            Assert.AreEqual(true, target.ModelState.IsValid);
        }
        public void Edit_HappyPath()
        {
            AnamnesesController controller;
            AnamneseViewModel   formModel;

            try
            {
                // obtains a valid patient
                Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db, 1);
                this.db.SaveChanges();
                var patientId = this.db.Patients.First().Id;

                formModel = new AnamneseViewModel()
                {
                    PatientId            = patientId,
                    Conclusion           = "This is my anamnese",
                    DiagnosticHypotheses = new List <DiagnosticHypothesisViewModel>()
                    {
                        new DiagnosticHypothesisViewModel()
                        {
                            Text = "Text", Cid10Code = "Q878"
                        },
                        new DiagnosticHypothesisViewModel()
                        {
                            Text = "Text2", Cid10Code = "Q879"
                        }
                    }
                };

                var mr = new MockRepository(true);
                controller = mr.CreateController <AnamnesesController>();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            // executing the test
            controller.Create(new[] { formModel });

            Assert.IsTrue(controller.ModelState.IsValid);

            var anamneses            = this.db.Anamnese.ToList();
            var diagnosticHypotheses = this.db.DiagnosticHypotheses.ToList();

            Assert.AreEqual(1, anamneses.Count);
            Assert.AreEqual(2, diagnosticHypotheses.Count);
        }
        public void LookupDiagnoses_1_ShouldReturnTheProperResult()
        {
            var mr         = new MockRepository(true);
            var controller = mr.CreateController <AnamnesesController>();

            var result           = controller.AutocompleteDiagnoses("cefaléia", 20, 1);
            var lookupJsonResult = (AutocompleteJsonResult)result.Data;

            Assert.AreEqual(9, lookupJsonResult.Count);
            foreach (CidAutocompleteGridModel item in lookupJsonResult.Rows)
            {
                Assert.IsNotNull(item.Cid10Code);
                Assert.IsFalse(string.IsNullOrEmpty(item.Cid10Name));
            }
        }
        public void EditPost_UserIsOwner_WithValidData()
        {
            PracticeHomeController homeController;
            var mr = new MockRepository();

            try
            {
                mr.SetCurrentUser_Andre_CorrectPassword();
                mr.SetRouteData_ConsultorioDrHouse_GregoryHouse(typeof(PracticeHomeController), "Edit");

                homeController = mr.CreateController <PracticeHomeController>(callOnActionExecuting: false);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            var viewModel = new PracticeHomeControllerViewModel
            {
                PracticeName     = "K!",
                PracticeTimeZone = 3,
                PhoneMain        = "(32)91272552",
                Address          = new AddressViewModel
                {
                    StateProvince = "MG",
                    CEP           = "36030-000",
                    City          = "Juiz de Fora",
                    Complement    = "Sta Luzia",
                    Street        = "Rua Sem Saída",
                }
            };

            Mvc3TestHelper.SetModelStateErrors(homeController, viewModel);

            // Execute test: owner must have access to this view.
            var actionResult = Mvc3TestHelper.RunOnAuthorization(homeController, "Edit", "POST")
                               ?? Mvc3TestHelper.RunOnActionExecuting(homeController, "Edit", "POST")
                               ?? homeController.Edit(viewModel);

            // Asserts
            Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));
            var redirectResult = (RedirectToRouteResult)actionResult;

            Assert.AreEqual(2, redirectResult.RouteValues.Count);
            Assert.AreEqual("practicehome", string.Format("{0}", redirectResult.RouteValues["controller"]), ignoreCase: true);
            Assert.AreEqual("Index", string.Format("{0}", redirectResult.RouteValues["action"]), ignoreCase: true);
        }
예제 #36
0
        public void Search_ShouldRespectTheSearchTermWhenItsPresent()
        {
            LaboratoriesController controller;

            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController <LaboratoriesController>();

                controller.Create(
                    new MedicineLaboratoryViewModel()
                {
                    Name = "Bash"
                });

                controller.Create(
                    new MedicineLaboratoryViewModel()
                {
                    Name = "Novartis"
                });
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            const string searchTerm = "ba";

            // making an empty search
            var result = controller.Search(
                new SearchModel()
            {
                Term = searchTerm,
                Page = 1
            });

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            var resultAsView = result as ViewResult;

            Debug.Assert(resultAsView != null, "resultAsView must not null");
            Assert.IsInstanceOfType(resultAsView.Model, typeof(SearchViewModel <MedicineLaboratoryViewModel>));
            var model = resultAsView.Model as SearchViewModel <MedicineLaboratoryViewModel>;

            Debug.Assert(model != null, "model must not be null");
            Assert.AreEqual(1, model.Count);
        }
        public void Search_ShouldRespectTheSearchTermWhenItsPresent()
        {
            LaboratoriesController controller;

            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController<LaboratoriesController>();

                controller.Create(
                    new MedicineLaboratoryViewModel()
                    {
                        Name = "Bash"
                    });

                controller.Create(
                    new MedicineLaboratoryViewModel()
                    {
                        Name = "Novartis"
                    });
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            const string searchTerm = "ba";

            // making an empty search
            var result = controller.Search(
                new SearchModel()
                {
                    Term = searchTerm,
                    Page = 1
                });

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            var resultAsView = result as ViewResult;

            Debug.Assert(resultAsView != null, "resultAsView must not null");
            Assert.IsInstanceOfType(resultAsView.Model, typeof(SearchViewModel<MedicineLaboratoryViewModel>));
            var model = resultAsView.Model as SearchViewModel<MedicineLaboratoryViewModel>;

            Debug.Assert(model != null, "model must not be null");
            Assert.AreEqual(1, model.Count);
        }
예제 #38
0
        public void AnvisaImport_HappyPath()
        {
            MedicinesController controller;
            SYS_Medicine        sysMedicine;

            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController <MedicinesController>();

                sysMedicine = this.db.SYS_Medicine.FirstOrDefault();
                if (sysMedicine == null)
                {
                    throw new Exception("SYS_Medicines are not populated");
                }
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            // todo: commented code - old test code, must remake this test
            //controller.AnvisaImport(
            //    new AnvisaImportViewModel()
            //    {
            //        AnvisaId = sysMedicine.Id,
            //        AnvisaText = sysMedicine.Name
            //    });

            var medicine = this.db.Medicines.FirstOrDefault(m => m.Name == sysMedicine.Name);

            Assert.IsNotNull(medicine);

            foreach (var activeIngredient in medicine.ActiveIngredients)
            {
                Assert.IsTrue(sysMedicine.ActiveIngredients.Any(ai => ai.Name == activeIngredient.Name));
            }

            foreach (var leaflet in medicine.Leaflets)
            {
                Assert.IsTrue(sysMedicine.Leaflets.Any(l => l.Url == leaflet.Url));
            }

            Assert.IsTrue(sysMedicine.Laboratory.Name == medicine.Laboratory.Name);
        }
예제 #39
0
        public void Search_ShouldReturnEverythingInEmptySearch()
        {
            LaboratoriesController controller;

            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController <LaboratoriesController>();

                controller.Create(
                    new MedicineLaboratoryViewModel()
                {
                    Name = "Lab1"
                });

                controller.Create(
                    new MedicineLaboratoryViewModel()
                {
                    Name = "Lab2"
                });
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // making an empty search
            var result = controller.Search(
                new SearchModel()
            {
                Term = "",
                Page = 1
            });

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            var resultAsView = result as ViewResult;

            Debug.Assert(resultAsView != null, "resultAsView must not be null");
            Assert.IsInstanceOfType(resultAsView.Model, typeof(SearchViewModel <MedicineLaboratoryViewModel>));
            var model = resultAsView.Model as SearchViewModel <MedicineLaboratoryViewModel>;

            Debug.Assert(model != null, "model must not be null");
            Assert.AreEqual(2, model.Count);
        }
        public void Delete_WhenTheresADiagnosis()
        {
            PatientsController controller;
            Patient patient;

            try
            {
                var docAndre = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(docAndre, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);
                var referenceTime = DateTime.UtcNow;

                var diagnosis = new Diagnosis()
                {
                    CreatedOn = referenceTime,
                    PatientId = patient.Id,
                    Cid10Code = "QAA",
                    Cid10Name = "Doença X", // x-men!
                    PracticeId = docAndre.PracticeId,
                };

                this.db.Diagnoses.AddObject(diagnosis);
                this.db.SaveChanges();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patient.Id);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patient.Id);
            Assert.IsNull(patient);
        }
        public void AnvisaImport_HappyPath()
        {
            MedicinesController controller;
            SYS_Medicine sysMedicine;
            try
            {
                var mr = new MockRepository(true);
                controller = mr.CreateController<MedicinesController>();

                sysMedicine = this.db.SYS_Medicine.FirstOrDefault();
                if (sysMedicine == null)
                    throw new Exception("SYS_Medicines are not populated");
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            // todo: commented code - old test code, must remake this test
            //controller.AnvisaImport(
            //    new AnvisaImportViewModel()
            //    {
            //        AnvisaId = sysMedicine.Id,
            //        AnvisaText = sysMedicine.Name
            //    });

            var medicine = this.db.Medicines.FirstOrDefault(m => m.Name == sysMedicine.Name);
            Assert.IsNotNull(medicine);

            foreach (var activeIngredient in medicine.ActiveIngredients)
                Assert.IsTrue(sysMedicine.ActiveIngredients.Any(ai => ai.Name == activeIngredient.Name));

            foreach (var leaflet in medicine.Leaflets)
                Assert.IsTrue(sysMedicine.Leaflets.Any(l => l.Url == leaflet.Url));

            Assert.IsTrue(sysMedicine.Laboratory.Name == medicine.Laboratory.Name);
        }
        public void Delete_WhenTheresAnAnamnese()
        {
            PatientsController controller;
            int patientId;
            Patient patient;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);

                patientId = patient.Id;

                // now, let's add an anamnese
                var anamnese = new Anamnese()
                {
                    PatientId = patientId,
                    CreatedOn = DateTime.UtcNow,
                    Conclusion = "This is my anamnese",
                    PracticeId = doctor.PracticeId,
                };

                patient.Anamneses.Add(anamnese);
                this.db.SaveChanges();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patientId);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patientId);
            Assert.IsNull(patient);
        }
        public void Edit_2_CannotSaveWithInvalidPatient()
        {
            var mr = new MockRepository(true);
            int modelId = this.db.ModelMedicalCertificates.First().Id;

            // tries to save
            var formModel = new MedicalCertificateViewModel()
            {
                ModelId = modelId,
                // this probably doesn't exist
                PatientId = 9999
            };

            var controller = mr.CreateController<MedicalCertificatesController>();
            var controllerResult = controller.Edit(new[] { formModel });

            Assert.IsInstanceOfType(controllerResult, typeof(ViewResult));
            Assert.AreEqual(false, controller.ModelState.IsValid);
            Assert.AreEqual(1, controller.ModelState.Count);
        }
        public void Search_ShouldReturnEverythingInEmptySearch()
        {
            PatientsController controller;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 100);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            var patientsCount = this.db.Patients.Count();

            // making an empty search
            var result = controller.Search(new Areas.App.Models.SearchModel()
            {
                Term = "",
                Page = 1
            });

            var resultAsView = result as ViewResult;
            Assert.IsNotNull(resultAsView);

            var model = resultAsView.Model as SearchViewModel<PatientViewModel>;
            Assert.IsNotNull(model);

            Assert.AreEqual(100, model.Count);
            Assert.AreEqual(Code.Constants.GRID_PAGE_SIZE, model.Objects.Count);
        }
예제 #45
0
        public void Create_WithoutMedicalProcedure()
        {
            ExamsController controller;
            Patient patient;
            bool isDbChangesSaved = false;
            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();
                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request without the text.
            // This is not allowed and must generate a model state validation message.
            ActionResult actionResult;
            ExaminationRequestViewModel viewModel;

            {
                viewModel = new ExaminationRequestViewModel
                {
                    PatientId = patient.Id,
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);

                actionResult = controller.Create(new[] { viewModel });
            }

            // Verifying the ActionResult, and the DB.
            // - The result must be a ViewResult, with the name "Edit".
            // - The controller ModelState must have one validation message.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            var viewResult = (ViewResult)actionResult;
            Assert.AreEqual("edit", viewResult.ViewName, ignoreCase: true);
            Assert.IsFalse(controller.ModelState.IsValid, "ModelState should not be valid.");
            Assert.AreEqual(
                1,
                controller.ModelState.GetPropertyErrors(() => viewModel.MedicalProcedureName).Count(),
                "ModelState should contain one validation message.");

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }
예제 #46
0
        public void Edit_1_HappyPath()
        {
            ExamsController controller;
            Patient patient;
            ExaminationRequest examRequest;
            DateTime utcNow;
            var localNow = new DateTime(2012, 08, 16);
            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();

                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>();
                Debug.Assert(doctor != null, "doctor must not be null");
                utcNow = PracticeController.ConvertToUtcDateTime(doctor.Users.First().Practice, localNow);
                controller.UtcNowGetter = () => utcNow;

                // saving the object that will be edited
                var medicalProc = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.03.04.36-1");
                examRequest = new ExaminationRequest
                {
                    CreatedOn = utcNow,
                    PatientId = patient.Id,
                    Text = "Old text",
                    MedicalProcedureCode = medicalProc.Code,
                    MedicalProcedureName = medicalProc.Name,
                    PracticeId = doctor.PracticeId,
                };
                this.db.ExaminationRequests.AddObject(examRequest);
                this.db.SaveChanges();
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request.
            ActionResult actionResult;

            {
                var medicalProc = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.01.03.23-4");
                var viewModel = new ExaminationRequestViewModel
                {
                    Id = examRequest.Id,
                    PatientId = patient.Id,
                    Notes = "Any text",
                    MedicalProcedureId = medicalProc.Id, // editing value: old = "4.03.04.36-1"; new = "4.01.03.23-4"
                    MedicalProcedureName = "Eletrencefalograma em vigília, e sono espontâneo ou induzido",
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);

                actionResult = controller.Edit(new[] { viewModel });
            }

            // Verifying the ActionResult.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");

            // Verifying the controller model-state.
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");

            // Verifying the database.
            using (var db2 = DbTestBase.CreateNewCerebelloEntities())
            {
                var obj = db2.ExaminationRequests.FirstOrDefault(x => x.PatientId == patient.Id);
                Assert.IsNotNull(obj, "Database record was not saved.");
                Assert.AreEqual("Any text", obj.Text);
                Assert.AreEqual(utcNow, obj.CreatedOn);
                Assert.AreEqual("4.01.03.23-4", obj.MedicalProcedureCode);
                Assert.AreEqual("Eletrencefalograma em vigília, e sono espontâneo ou induzido", obj.MedicalProcedureName);
            }
        }
예제 #47
0
        public void LookupEverything_1_ShouldSearchPatients()
        {
            var doctor = this.db.Doctors.First();

            // create some fake patients
            // patient 1
            Patient patient1 = new Patient()
            {
                Person = new Person()
                {
                    FullName = "Joao Manuel da Silva",
                    Gender = (int)TypeGender.Male,
                    DateOfBirth = Firestarter.ConvertFromDefaultToUtc(new DateTime(1982, 10, 12)),
                    MaritalStatus = (int)TypeMaritalStatus.Casado,
                    BirthPlace = "Brasileiro",
                    CPF = "87324128910",
                    CPFOwner = (int)TypeCpfOwner.PatientItself,
                    Profession = "Encarregado de Obras",
                    CreatedOn = DateTime.UtcNow,
                    PracticeId = doctor.PracticeId,
                },
                Doctor = doctor,
                PracticeId = doctor.PracticeId,
            };
            patient1.Person.Email = "*****@*****.**";
            patient1.Person.Addresses.Add(
                new Address
                    {
                        CEP = "602500330",
                        StateProvince = "RJ",
                        City = "Rio de Janeiro",
                        Neighborhood = "Jacarepaguá",
                        Street = "Rua Estrada do Pau Ferro 329",
                        Complement = "",
                        PracticeId = doctor.PracticeId,
                    });

            db.Patients.AddObject(patient1);

            Patient patient2 = new Patient()
            {
                Person = new Person()
                {
                    FullName = "Manuela Moreira da Silva",
                    Gender = (int)TypeGender.Female,
                    DateOfBirth = Firestarter.ConvertFromDefaultToUtc(new DateTime(1982, 10, 12)),
                    MaritalStatus = (int)TypeMaritalStatus.Casado,
                    BirthPlace = "Brasileiro",
                    CPF = "87324128910",
                    CPFOwner = (int)TypeCpfOwner.PatientItself,
                    Profession = "Encarregado de Obras",
                    CreatedOn = DateTime.UtcNow,
                    PracticeId = doctor.PracticeId,
                },
                Doctor = doctor
            };
            patient1.Person.Email = "*****@*****.**";
            patient1.Person.Addresses.Add(
                new Address
                    {
                        CEP = "602500330",
                        StateProvince = "RJ",
                        City = "Rio de Janeiro",
                        Neighborhood = "Jacarepaguá",
                        Street = "Rua Estrada do Pau Ferro 329",
                        Complement = "",
                        PracticeId = doctor.PracticeId,
                    });

            db.Patients.AddObject(patient2);

            this.db.SaveChanges();

            var mr = new MockRepository(true);
            var controller = mr.CreateController<AppController>();
            var controllerResult = controller.LookupEverything("Joao", 20, 1, this.db.Doctors.First().Id);

            var controllerResultAsLookupResult = (AutocompleteJsonResult)controllerResult.Data;

            Assert.AreEqual(1, controllerResultAsLookupResult.Rows.Count);
            Assert.IsInstanceOfType(controllerResultAsLookupResult.Rows[0], typeof(GlobalSearchViewModel));

            Assert.AreEqual(patient1.Person.FullName, ((GlobalSearchViewModel)controllerResultAsLookupResult.Rows[0]).Value);
            Assert.AreEqual(patient1.Id, ((GlobalSearchViewModel)controllerResultAsLookupResult.Rows[0]).Id);
        }
예제 #48
0
        public void Edit_2_WithoutMedicalProcedure()
        {
            ExamsController controller;
            Patient patient;
            ExaminationRequest examRequest;
            var isDbChangesSaved = false;
            var localNow = new DateTime(2012, 08, 16);
            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();
                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
                Debug.Assert(doctor != null, "doctor must not be null");
                var utcNow = PracticeController.ConvertToUtcDateTime(doctor.Users.First().Practice, localNow);
                controller.UtcNowGetter = () => utcNow;

                // saving the object that will be edited
                examRequest = new ExaminationRequest
                {
                    CreatedOn = utcNow,
                    PatientId = patient.Id,
                    Text = "Old text",
                    PracticeId = doctor.PracticeId,
                    MedicalProcedureName = "Hemoglobina (eletroforese ou HPLC)",
                    MedicalProcedureCode = "4.03.04.35-3",
                };
                this.db.ExaminationRequests.AddObject(examRequest);
                this.db.SaveChanges();
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request without the text.
            // This is not allowed and must generate a model state validation message.
            ActionResult actionResult;
            ExaminationRequestViewModel viewModel;

            {
                viewModel = new ExaminationRequestViewModel
                {
                    Id = examRequest.Id,
                    PatientId = patient.Id,
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);

                actionResult = controller.Edit(new[] { viewModel });
            }

            // Verifying the ActionResult, and the DB.
            // - The result must be a ViewResult, with the name "Edit".
            // - The controller ModelState must have one validation message.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            var viewResult = (ViewResult)actionResult;
            Assert.AreEqual("edit", viewResult.ViewName, true);
            Assert.IsFalse(controller.ModelState.IsValid, "ModelState should not be valid.");
            Assert.AreEqual(
                1,
                controller.ModelState.GetPropertyErrors(() => viewModel.MedicalProcedureName).Count(),
                "ModelState should contain one validation message.");

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }
예제 #49
0
        public void Edit_4_EditExamThatDoesNotExist()
        {
            ExamsController controller;
            ExaminationRequestViewModel viewModel;
            var isDbChangesSaved = false;
            var localNow = new DateTime(2012, 08, 16);
            try
            {
                var drandre = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var patient = Firestarter.CreateFakePatients(drandre, this.db).First();

                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
                Debug.Assert(drandre != null, "drandre must not be null");
                var utcNow = PracticeController.ConvertToUtcDateTime(drandre.Users.First().Practice, localNow);
                controller.UtcNowGetter = () => utcNow;

                // saving the object that will be edited
                var medicalProc0 = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.03.04.36-1");
                var examRequest = new ExaminationRequest
                                      {
                                          CreatedOn = utcNow,
                                          PatientId = patient.Id,
                                          Text = "Old text",
                                          MedicalProcedureCode = medicalProc0.Code,
                                          MedicalProcedureName = medicalProc0.Name,
                                          PracticeId = drandre.PracticeId,
                                      };
                this.db.ExaminationRequests.AddObject(examRequest);
                this.db.SaveChanges();

                // Define André as the logged user.
                mr.SetCurrentUser_Andre_CorrectPassword();

                // Creating view-model and setting up controller ModelState based on the view-model.
                var medicalProc1 = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.01.03.23-4");
                viewModel = new ExaminationRequestViewModel
                {
                    Id = 19837,
                    PatientId = patient.Id,
                    Notes = "New text",
                    MedicalProcedureCode = medicalProc1.Code,
                    MedicalProcedureName = medicalProc1.Name,
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Editing an examination request that does not belong to the current user's practice.
            // This is not allowed and must throw an exception.
            // note: this is not a validation error, this is a malicious attack...
            ActionResult actionResult = controller.Edit(new[] { viewModel });

            // Verifying the ActionResult, and the DB.
            // - The result must be a ViewResult, with the name "Edit".
            // - The controller ModelState must have one validation message.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            var viewResult = (ViewResult)actionResult;
            Assert.AreEqual("NotFound", viewResult.ViewName);

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }
        public void Edit_HappyPath()
        {
            AnamnesesController controller;
            AnamneseViewModel formModel;
            try
            {
                // obtains a valid patient
                Firestarter.CreateFakePatients(this.db.Doctors.First(), this.db, 1);
                this.db.SaveChanges();
                var patientId = this.db.Patients.First().Id;

                formModel = new AnamneseViewModel()
                    {
                        PatientId = patientId,
                        Conclusion = "This is my anamnese",
                        DiagnosticHypotheses = new List<DiagnosticHypothesisViewModel>()
                            {
                                new DiagnosticHypothesisViewModel() {Text = "Text", Cid10Code = "Q878"},
                                new DiagnosticHypothesisViewModel() {Text = "Text2", Cid10Code = "Q879"}
                            }
                    };

                var mr = new MockRepository(true);
                controller = mr.CreateController<AnamnesesController>();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            // executing the test
            controller.Create(new[] { formModel });

            Assert.IsTrue(controller.ModelState.IsValid);

            var anamneses = this.db.Anamnese.ToList();
            var diagnosticHypotheses = this.db.DiagnosticHypotheses.ToList();

            Assert.AreEqual(1, anamneses.Count);
            Assert.AreEqual(2, diagnosticHypotheses.Count);
        }
        public void Delete_WhenTheresAnAppointment()
        {
            PatientsController controller;
            Patient patient;

            try
            {
                var docAndre = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(docAndre, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);
                var referenceTime = DateTime.UtcNow;

                var appointment = new Appointment()
                {
                    Doctor = docAndre,
                    CreatedBy = docAndre.Users.First(),
                    CreatedOn = referenceTime,
                    PatientId = patient.Id,
                    Start = referenceTime,
                    End = referenceTime + TimeSpan.FromMinutes(30),
                    PracticeId = docAndre.PracticeId,
                };

                this.db.Appointments.AddObject(appointment);
                this.db.SaveChanges();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patient.Id);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patient.Id);
            Assert.IsNull(patient);
        }
        public void Delete_WhenTheresNoAssociation()
        {
            PatientsController controller;
            int patientId;
            Patient patient;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);
                patientId = patient.Id;
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patientId);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patientId);
            Assert.IsNull(patient);
        }
        public void Delete_WhenTheresAnExamResult()
        {
            PatientsController controller;
            int patientId;
            Patient patient;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);

                patientId = patient.Id;

                var examResult = new ExaminationResult()
                {
                    MedicalProcedureCode = "mcode",
                    MedicalProcedureName = "mname",
                    PatientId = patientId,
                    CreatedOn = DateTime.UtcNow,
                    Text = "tudo deu certo",
                    PracticeId = doctor.PracticeId,
                };

                this.db.SYS_MedicalProcedure.AddObject(
                    new SYS_MedicalProcedure()
                        {
                            Code = "mcode",
                            Name = "mname"
                        });

                this.db.ExaminationResults.AddObject(examResult);

                this.db.SaveChanges();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patientId);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patientId);
            Assert.IsNull(patient);
        }
        public void LookupDiagnoses_1_ShouldReturnTheProperResult()
        {
            var mr = new MockRepository(true);
            var controller = mr.CreateController<AnamnesesController>();

            var result = controller.AutocompleteDiagnoses("cefaléia", 20, 1);
            var lookupJsonResult = (AutocompleteJsonResult)result.Data;

            Assert.AreEqual(9, lookupJsonResult.Count);
            foreach (CidAutocompleteGridModel item in lookupJsonResult.Rows)
            {
                Assert.IsNotNull(item.Cid10Code);
                Assert.IsFalse(string.IsNullOrEmpty(item.Cid10Name));
            }
        }
        public void Delete_WhenTheresAReceipt()
        {
            PatientsController controller;
            int patientId;
            Patient patient;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);

                patientId = patient.Id;

                var medicine = new Medicine()
                    {
                        Laboratory = new Laboratory()
                        {
                            Name = "Lab1",
                            Doctor = doctor
                        },
                        Name = "Med1",
                        Doctor = doctor,
                        PracticeId = doctor.PracticeId,
                    };

                medicine.ActiveIngredients.Add(new MedicineActiveIngredient()
                    {
                        Name = "AI1",
                        PracticeId = doctor.PracticeId,
                    });

                this.db.Medicines.AddObject(medicine);

                // now, let's add an receipt
                var receipt = new Receipt()
                {
                    PatientId = patientId,
                    CreatedOn = DateTime.UtcNow,
                    PracticeId = doctor.PracticeId,
                };

                receipt.ReceiptMedicines.Add(new ReceiptMedicine()
                    {
                        Medicine = medicine,
                        Quantity = "1 caixa",
                        Prescription = "toma 1 de manha",
                        PracticeId = doctor.PracticeId,
                    });

                this.db.Receipts.AddObject(receipt);

                this.db.SaveChanges();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patientId);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patientId);
            Assert.IsNull(patient);
        }
예제 #56
0
        public void Delete_1_HappyPath()
        {
            ExamsController controller;
            Patient patient;
            ExaminationRequest examRequest;
            var isDbChangesSaved = false;
            var localNow = new DateTime(2012, 08, 16);
            try
            {
                using (var db2 = DbTestBase.CreateNewCerebelloEntities())
                {
                    var drandre = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(db2);
                    patient = Firestarter.CreateFakePatients(drandre, db2).First();

                    var mr = new MockRepository(true);
                    controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
                    Debug.Assert(drandre != null, "drandre must not be null");
                    var utcNow = PracticeController.ConvertToUtcDateTime(drandre.Users.First().Practice, localNow);
                    controller.UtcNowGetter = () => utcNow;

                    // saving the object that will be edited
                    var medicalProc1 = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.01.03.55-2");

                    examRequest = new ExaminationRequest
                                      {
                                          PracticeId = patient.PracticeId,
                                          CreatedOn = utcNow,
                                          PatientId = patient.Id,
                                          Text = "Old text",
                                          MedicalProcedureCode = medicalProc1.Code,
                                          MedicalProcedureName = medicalProc1.Name
                                      };

                    db2.ExaminationRequests.AddObject(examRequest);
                    db2.SaveChanges();

                    // Define André as the logged user, he cannot edit Marta's patients.
                    mr.SetCurrentUser_Andre_CorrectPassword();
                }
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Editing an examination request that does not belong to the current user's practice.
            // This is not allowed and must throw an exception.
            // note: this is not a validation error, this is a malicious attack...
            ActionResult actionResult = controller.Delete(examRequest.Id);

            // Verifying the ActionResult.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");

            // Verifying the controller model-state.
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");

            // Verifying the database: cannot save the changes.
            Assert.IsTrue(isDbChangesSaved, "Database changes were not saved, but they should.");

            // Verifying the database.
            using (var db2 = DbTestBase.CreateNewCerebelloEntities())
            {
                var obj = db2.ExaminationRequests.FirstOrDefault(x => x.PatientId == patient.Id);
                Assert.IsNull(obj, "Database record was not deleted.");
            }
        }
        public void Search_ShouldRespectTheSearchTermWhenItsPresent()
        {
            PatientsController controller = null;

            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 200);
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
            }

            var searchTerm = "an";
            var matchingPatientsCount = this.db.Patients.Count(p => p.Person.FullName.Contains(searchTerm));

            // making an empty search
            var result = controller.Search(new Areas.App.Models.SearchModel()
            {
                Term = searchTerm,
                Page = 1
            });

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            var resultAsView = result as ViewResult;

            Assert.IsInstanceOfType(resultAsView.Model, typeof(SearchViewModel<PatientViewModel>));
            var model = resultAsView.Model as SearchViewModel<PatientViewModel>;

            Assert.AreEqual(matchingPatientsCount, model.Count);
            Assert.IsTrue(model.Objects.Count >= Code.Constants.GRID_PAGE_SIZE);
        }
예제 #58
0
        public void Delete_2_ExamThatDoesNotExist()
        {
            ExamsController controller;
            bool isDbChangesSaved = false;
            try
            {
                using (var db2 = DbTestBase.CreateNewCerebelloEntities())
                {
                    Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(db2);

                    var mr = new MockRepository(true);
                    controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });

                    // Define André as the logged user, he cannot edit Marta's patients.
                    mr.SetCurrentUser_Andre_CorrectPassword();
                }
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Editing an examination request that does not belong to the current user's practice.
            // This is not allowed and must throw an exception.
            // note: this is not a validation error, this is a malicious attack...
            var jsonResult = controller.Delete(6327);

            // Verifying the ActionResult.
            Assert.IsNotNull(jsonResult, "The result of the controller method is null.");
            var jsonDelete = (JsonDeleteMessage)jsonResult.Data;
            Assert.IsFalse(jsonDelete.success, "Deletion should not succed.");
            Assert.IsNotNull(jsonDelete.text, "Deletion should fail with a message.");

            // Verifying the controller model-state.
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }
        public void Delete_WhenTheresAMedicalCertificate()
        {
            PatientsController controller;
            Doctor doctor;
            Patient patient;

            try
            {
                doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var mr = new MockRepository(true);
                controller = mr.CreateController<PatientsController>();
                Firestarter.CreateFakePatients(doctor, this.db, 1);

                // we now have 1 patient
                patient = this.db.Patients.FirstOrDefault();
                Assert.IsNotNull(patient);

                var certificateModel = new Cerebello.Model.ModelMedicalCertificate()
                {
                    DoctorId = doctor.Id,
                    Name = "model1",
                    Text = "model1",
                    PracticeId = doctor.PracticeId,
                };

                certificateModel.Fields.Add(new ModelMedicalCertificateField()
                {
                    Name = "field1",
                    PracticeId = doctor.PracticeId,
                });

                var certificate = new Cerebello.Model.MedicalCertificate()
                {
                    ModelMedicalCertificate = certificateModel,
                    Patient = patient,
                    Text = "text",
                    CreatedOn = DateTime.UtcNow,
                    PracticeId = doctor.PracticeId,
                };

                certificate.Fields.Add(new MedicalCertificateField()
                {
                    Name = "field1",
                    Value = "value",
                    PracticeId = doctor.PracticeId,
                });

                this.db.MedicalCertificates.AddObject(certificate);
                this.db.SaveChanges();
            }
            catch
            {
                Assert.Inconclusive("Test initialization has failed.");
                return;
            }

            controller.Delete(patient.Id);

            // this patient must have been deleted
            patient = this.db.Patients.FirstOrDefault(p => p.Id == patient.Id);
            Assert.IsNull(patient);
        }
예제 #60
0
        public void Delete_3_ExamFromAnotherPractice()
        {
            ExamsController controller;
            ExaminationRequest examRequest;
            var isDbChangesSaved = false;
            var localNow = new DateTime(2012, 08, 16);
            try
            {
                var drandre = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var dramarta = Firestarter.Create_CrmMg_Psiquiatria_DraMarta_Marta(this.db);
                var patientDraMarta = Firestarter.CreateFakePatients(dramarta, this.db).First();

                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
                Debug.Assert(drandre != null, "drandre must not be null");
                var utcNow = PracticeController.ConvertToUtcDateTime(drandre.Users.First().Practice, localNow);
                controller.UtcNowGetter = () => utcNow;

                // saving the object that will be edited
                var medicalProc0 = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.03.04.36-1");
                examRequest = new ExaminationRequest
                {
                    CreatedOn = utcNow,
                    PatientId = patientDraMarta.Id,
                    Text = "Old text",
                    MedicalProcedureCode = medicalProc0.Code,
                    MedicalProcedureName = medicalProc0.Name,
                    PracticeId = dramarta.PracticeId,
                };
                this.db.ExaminationRequests.AddObject(examRequest);
                this.db.SaveChanges();

                // Define André as the logged user, he cannot edit Marta's patients.
                mr.SetCurrentUser_Andre_CorrectPassword();
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Editing an examination request that does not belong to the current user's practice.
            // This is not allowed and must throw an exception.
            // note: this is not a validation error, this is a malicious attack...
            var jsonResult = controller.Delete(examRequest.Id);

            // Verifying the ActionResult.
            Assert.IsNotNull(jsonResult, "The result of the controller method is null.");
            var jsonDelete = (JsonDeleteMessage)jsonResult.Data;
            Assert.IsFalse(jsonDelete.success, "Deletion should not succed.");
            Assert.IsNotNull(jsonDelete.text, "Deletion should fail with a message.");

            // Verifying the controller model-state.
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }