Beispiel #1
0
    def post(self):
        username = self.get_argument("username", "").strip().lower()
        passwd = self.get_argument("password", "")
        nextpage = self.get_argument("next", None)
        if nextpage is None:
            if "auth/" not in self.request.headers['Referer']:
                nextpage = self.request.headers['Referer']
            else:
                nextpage = "%s/" % qiita_config.portal_dir

        msg = ""
        # check the user level
        try:
            if User(username).level == "unverified":
                # email not verified so dont log in
                msg = ("Email not verified. Please check your email and click "
                       "the verify link. You may need to check your spam "
                       "folder to find the email.<br/>If a verification email"
                       " has not arrived in 15 minutes, please email <a href='"
                       "mailto:[email protected]'>[email protected]</a>")
        except QiitaDBUnknownIDError:
            msg = "Unknown user"
        except RuntimeError:
            # means DB not available, so set maintenance mode and failover
            r_client.set("maintenance", "Database connection unavailable, "
                         "please try again later.")
            self.redirect("%s/" % qiita_config.portal_dir)
            return

        # Check the login information
        login = None
        try:
            login = User.login(username, passwd)
        except IncorrectEmailError:
            msg = "Unknown user"
        except IncorrectPasswordError:
            msg = "Incorrect password"
        except UnverifiedEmailError:
            msg = "You have not verified your email address"

        if login:
            # everything good so log in
            self.set_current_user(username)
            self.redirect(nextpage)
        else:
            self.render("index.html", message=msg, level='danger')
Beispiel #2
0
def prep_template_summary_get_req(prep_id, user_id):
    """Get the summarized prep template data for each metadata column

    Parameters
    ----------
    prep_id : int
        PrepTemplate id to get info for
    user_id : str
        User requesting the sample template info

    Returns
    -------
    dict of objects
        Dictionary object where the keys are the metadata categories
        and the values are list of tuples. Each tuple is an observed value in
        the category and the number of times its seen.
        Format {'status': status,
                'message': message,
                'num_samples': value,
                'category': [(val1, count1), (val2, count2), ...],
                'editable': bool}
    """
    exists = _check_prep_template_exists(int(prep_id))
    if exists['status'] != 'success':
        return exists

    prep = PrepTemplate(int(prep_id))
    access_error = check_access(prep.study_id, user_id)
    if access_error:
        return access_error

    editable = Study(prep.study_id).can_edit(User(user_id))
    df = prep.to_dataframe()
    out = {'num_samples': df.shape[0],
           'summary': [],
           'status': 'success',
           'message': '',
           'editable': editable}

    cols = sorted(list(df.columns))
    for column in cols:
        counts = df[column].value_counts()
        out['summary'].append(
            (str(column), [(str(key), counts[key])
                           for key in natsorted(counts.index)]))
    return out
Beispiel #3
0
    def test_get(self):
        DefaultWorkflow(2).active = False
        response = self.get('/workflows/')
        self.assertEqual(response.code, 200)
        body = response.body.decode('ascii')
        self.assertNotEqual(body, "")
        # checking that this software is not displayed
        self.assertNotIn('FASTA upstream workflow', body)

        BaseHandler.get_current_user = Mock(return_value=User("*****@*****.**"))
        response = self.get('/workflows/')
        self.assertEqual(response.code, 200)
        body = response.body.decode('ascii')
        self.assertNotEqual(body, "")
        # checking that this software is displayed
        self.assertIn('FASTA upstream workflow', body)
        DefaultWorkflow(2).active = True
    def test_get(self):
        response = self.get('/study/description/sample_template/',
                            {'study_id': 1})
        self.assertEqual(response.code, 200)
        self.assertNotEqual(response.body, "")

        # Study doesn't exist
        response = self.get('/study/description/sample_template/',
                            {'study_id': 10000})
        self.assertEqual(response.code, 404)

        # User doesn't have access
        BaseHandler.get_current_user = Mock(
            return_value=User('*****@*****.**'))
        response = self.get('/study/description/sample_template/',
                            {'study_id': 1})
        self.assertEqual(response.code, 403)
Beispiel #5
0
    def test_create_sample_template(self):
        # Test error
        job = self._create_job(
            'create_sample_template', {
                'fp': self.fp,
                'study_id': 1,
                'is_mapping_file': False,
                'data_type': None
            })
        private_task(job.id)
        self.assertEqual(job.status, 'error')
        self.assertIn(
            "The 'SampleTemplate' object with attributes (id: 1) "
            "already exists.", job.log.msg)

        # Test success with a warning
        info = {
            "timeseries_type_id": '1',
            "metadata_complete": 'true',
            "mixs_compliant": 'true',
            "study_alias": "TDST",
            "study_description": "Test create sample template",
            "study_abstract": "Test create sample template",
            "principal_investigator_id": StudyPerson(1)
        }
        study = Study.create(User('*****@*****.**'),
                             "Create Sample Template test", info)
        job = self._create_job(
            'create_sample_template', {
                'fp': self.fp,
                'study_id': study.id,
                'is_mapping_file': False,
                'data_type': None
            })
        private_task(job.id)
        self.assertEqual(job.status, 'success')
        obs = r_client.get("sample_template_%d" % study.id)
        self.assertIsNotNone(obs)
        obs = loads(obs)
        self.assertCountEqual(obs, ['job_id', 'alert_type', 'alert_msg'])
        self.assertEqual(obs['job_id'], job.id)
        self.assertEqual(obs['alert_type'], 'warning')
        self.assertIn(
            'Some functionality will be disabled due to missing columns:',
            obs['alert_msg'])
Beispiel #6
0
    def test_delete_sample_template(self):
        # Error case
        job = self._create_job('delete_sample_template', {'study': 1})
        private_task(job.id)
        self.assertEqual(job.status, 'error')
        self.assertIn(
            "Sample template cannot be erased because there are "
            "prep templates associated", job.log.msg)

        # Success case
        info = {
            "timeseries_type_id": '1',
            "metadata_complete": 'true',
            "mixs_compliant": 'true',
            "study_alias": "TDST",
            "study_description": "Test delete sample template",
            "study_abstract": "Test delete sample template",
            "principal_investigator_id": StudyPerson(1)
        }
        study = Study.create(User('*****@*****.**'),
                             "Delete Sample Template test", info)
        metadata = pd.DataFrame.from_dict(
            {
                'Sample1': {
                    'physical_specimen_location': 'location1',
                    'physical_specimen_remaining': 'true',
                    'dna_extracted': 'true',
                    'sample_type': 'type1',
                    'collection_timestamp': '2014-05-29 12:24:15',
                    'host_subject_id': 'NotIdentified',
                    'Description': 'Test Sample 1',
                    'latitude': '42.42',
                    'longitude': '41.41',
                    'taxon_id': '9606',
                    'scientific_name': 'h**o sapiens'
                }
            },
            orient='index',
            dtype=str)
        SampleTemplate.create(metadata, study)

        job = self._create_job('delete_sample_template', {'study': study.id})
        private_task(job.id)
        self.assertEqual(job.status, 'success')
        self.assertFalse(SampleTemplate.exists(study.id))
Beispiel #7
0
    def post(self):
        passmsg = ""
        msg = ""
        user = User(self.current_user)
        action = self.get_argument("action")
        if action == "profile":
            # tuple of colmns available for profile
            # FORM INPUT NAMES MUST MATCH DB COLUMN NAMES
            form_data = UserProfile()
            form_data.process(data=self.request.arguments)
            profile = {
                name: data[0]
                for name, data in viewitems(form_data.data)
            }

            # Turn default value as list into default strings
            for field in form_data:
                field.data = field.data[0]
            try:
                user.info = profile
                msg = "Profile updated successfully"
            except Exception as e:
                msg = "ERROR: profile could not be updated"
                LogEntry.create('Runtime',
                                "Cound not update profile: %s" % str(e),
                                info={'User': user.id})

        elif action == "password":
            profile = user.info
            oldpass = self.get_argument("oldpass")
            newpass = self.get_argument("newpass")
            try:
                user.change_password(oldpass, newpass)
            except Exception as e:
                passmsg = "ERROR: could not change password"
                LogEntry.create('Runtime',
                                "Cound not change password: %s" % str(e),
                                info={'User': user.id})
            else:
                passmsg = "Password changed successfully"
        self.render("user_profile.html",
                    user=user.id,
                    profile=form_data,
                    msg=msg,
                    passmsg=passmsg)
Beispiel #8
0
    def get(self, jti):
        # Grab the jwt out of the database
        jwt = DownloadLink.get(jti)

        # If no jwt, error response
        if jwt is None:
            raise HTTPError(
                404,
                reason='Download Not Found.  Link may have expired.')

        # If jwt doesn't validate, error response
        jwt_data = jose_jwt.decode(jwt, qiita_config.jwt_secret, 'HS256')
        if jwt_data is None:
            raise HTTPError(403, reason='Invalid JWT')

        # Triple check expiration and user permissions
        user = User(jwt_data["sub"])
        artifact = Artifact(jwt_data["artifactId"])

        utc_millis = datetime.now(timezone.utc).timestamp() * 1000

        if utc_millis < jwt_data["iat"]:
            raise HTTPError(403, reason="This download link is not yet valid")
        if utc_millis > jwt_data["exp"]:
            raise HTTPError(403, reason="This download link has expired")
        if jwt_data["perm"] != "download":
            raise HTTPError(403, reason="This download link is invalid")

        check_artifact_access(user, artifact)

        # All checks out, let's give them the files then!
        to_download = self._list_artifact_files_nginx(artifact)
        if not to_download:
            raise HTTPError(422, reason='Nothing to download. If '
                                        'this is a mistake contact: '
                                        '*****@*****.**')
        else:
            self._write_nginx_file_list(to_download)

            zip_fn = 'artifact_%s_%s.zip' % (
                jwt_data["artifactId"], datetime.now().strftime(
                    '%m%d%y-%H%M%S'))

            self._set_nginx_headers(zip_fn)
            self.finish()
Beispiel #9
0
    def test_get_deselected(self):
        a = Analysis(1)
        u = User('*****@*****.**')
        args = {'deselected': u.id, 'id': a.id}
        self.assertEqual(a.shared_with, [u])
        response = self.get('/analysis/sharing/', args)
        self.assertEqual(response.code, 200)
        exp = {'users': [], 'links': ''}
        self.assertEqual(loads(response.body), exp)
        self.assertEqual(a.shared_with, [])

        # Make sure unshared message added to the system
        self.assertEqual(
            'Analysis \'SomeAnalysis\' has been unshared from '
            'you.',
            u.messages()[0][1])
        # Share the analysis back with the user
        a.share(u)
Beispiel #10
0
    def test_get_deselected(self):
        s = Study(1)
        u = User('*****@*****.**')
        args = {'deselected': u.id, 'id': s.id}
        self.assertEqual(s.shared_with, [u])
        response = self.get('/study/sharing/', args)
        self.assertEqual(response.code, 200)
        exp = {'users': [], 'links': ''}
        self.assertEqual(loads(response.body), exp)
        self.assertEqual(s.shared_with, [])

        # Make sure unshared message added to the system
        self.assertEqual(
            'Study \'Identification of the Microbiomes for '
            'Cannabis Soils\' has been unshared from you.',
            u.messages()[0][1])
        # Share the study back with the user
        s.share(u)
Beispiel #11
0
    def __call__(self, searchstr, user):
        """Runs a Study query and returns matching studies and samples

        Parameters
        ----------
        searchstr : str
            Search string to use
        user : str
            User making the search. Needed for permissions checks.

        Returns
        -------
        dict
            Found samples in format
            {study_id: [[samp_id1, meta1, meta2, ...],
                        [samp_id2, meta1, meta2, ...], ...}
        list
            metadata column names searched for

        Notes
        -----
        Metadata information for each sample is in the same order as the
        metadata columns list returned

        Metadata column names and string searches are case-sensitive
        """
        study_sql, sample_sql, meta_headers = \
            self._parse_study_search_string(searchstr)
        conn_handler = SQLConnectionHandler()
        # get all studies containing the metadata headers requested
        study_ids = {x[0] for x in conn_handler.execute_fetchall(study_sql)}
        # strip to only studies user has access to
        userobj = User(user)
        study_ids = study_ids.intersection(Study.get_public() +
                                           userobj.private_studies +
                                           userobj.shared_studies)
        results = {}
        # run search on each study to get out the matching samples
        for sid in study_ids:
            study_res = conn_handler.execute_fetchall(sample_sql.format(sid))
            if study_res:
                # only add study to results if actually has samples in results
                results[sid] = study_res
        return results, meta_headers
Beispiel #12
0
    def test_create_parent(self):
        sql = "SELECT EXTRACT(EPOCH FROM NOW())"
        time1 = float(self.conn_handler.execute_fetchall(sql)[0][0])

        new = Analysis.create(User("*****@*****.**"), "newAnalysis",
                              "A New Analysis", Analysis(1))
        self.assertEqual(new.id, 3)
        sql = ("SELECT analysis_id, email, name, description, "
               "analysis_status_id, pmid, EXTRACT(EPOCH FROM timestamp) "
               "FROM qiita.analysis WHERE analysis_id = 3")
        obs = self.conn_handler.execute_fetchall(sql)
        self.assertEqual(
            obs[0][:-1],
            [3, '*****@*****.**', 'newAnalysis', 'A New Analysis', 1, None])
        self.assertTrue(time1 < float(obs[0][-1]))

        sql = "SELECT * FROM qiita.analysis_chain WHERE child_id = 3"
        obs = self.conn_handler.execute_fetchall(sql)
        self.assertEqual(obs, [[1, 3]])
 def setUp(self):
     info = {
         "timeseries_type_id": 1,
         "metadata_complete": True,
         "mixs_compliant": True,
         "number_samples_collected": 25,
         "number_samples_promised": 28,
         "study_alias": "FCM",
         "study_description": "Microbiome of people who eat nothing but "
         "fried chicken",
         "study_abstract": "Exploring how a high fat diet changes the "
         "gut microbiome",
         "emp_person_id": StudyPerson(2),
         "principal_investigator_id": StudyPerson(3),
         "lab_person_id": StudyPerson(1)
     }
     self.new_study = Study.create(User('*****@*****.**'),
                                   "Fried Chicken Microbiome", [1], info)
     self._clean_up_files = []
Beispiel #14
0
    def test_create_study_min_data(self):
        """Insert a study into the database"""
        obs = Study.create(User('*****@*****.**'), "Fried chicken microbiome",
                           [1], self.info)
        self.assertEqual(obs.id, 2)
        exp = {
            'mixs_compliant': True,
            'metadata_complete': True,
            'reprocess': False,
            'study_status_id': 1,
            'number_samples_promised': 28,
            'emp_person_id': 2,
            'funding': None,
            'vamps_id': None,
            'first_contact': date.today().isoformat(),
            'principal_investigator_id': 3,
            'timeseries_type_id': 1,
            'study_abstract': 'Exploring how a high fat diet changes the '
            'gut microbiome',
            'email': '*****@*****.**',
            'spatial_series': None,
            'study_description': 'Microbiome of people who eat nothing but'
            ' fried chicken',
            'portal_type_id': 3,
            'study_alias': 'FCM',
            'study_id': 2,
            'most_recent_contact': None,
            'lab_person_id': 1,
            'study_title': 'Fried chicken microbiome',
            'number_samples_collected': 25
        }

        obsins = self.conn_handler.execute_fetchall(
            "SELECT * FROM qiita.study WHERE study_id = 2")
        self.assertEqual(len(obsins), 1)
        obsins = dict(obsins[0])
        self.assertEqual(obsins, exp)

        # make sure EFO went in to table correctly
        efo = self.conn_handler.execute_fetchall(
            "SELECT efo_id FROM qiita.study_experimental_factor "
            "WHERE study_id = 2")
        self.assertEqual(efo, [[1]])
Beispiel #15
0
    def test_post_create_analysis_handler(self):
        user = User('*****@*****.**')
        dflt_analysis = user.default_analysis
        dflt_analysis.add_samples(
            {4: ['1.SKB8.640193', '1.SKD8.640184', '1.SKB7.640196',
                 '1.SKM9.640192', '1.SKM4.640180']})
        args = {'name': 'New Test Analysis',
                'description': 'Test Analysis Description'}
        response = self.post('/analysis/create/', args)
        self.assertRegexpMatches(
            response.effective_url,
            r"http://localhost:\d+/analysis/description/\d+/")
        self.assertEqual(response.code, 200)

        # The new analysis id is located at the -2 position (see regex above)
        new_id = response.effective_url.split('/')[-2]
        a = Analysis(new_id)
        # Make sure that all jobs have completed before we exit this tests
        for j in a.jobs:
            wait_for_processing_job(j.id)
Beispiel #16
0
    def test_post_edit_blank_doi(self):
        study_count_before = get_count('qiita.study')
        study = Study(1)
        study_info = study.info

        post_data = {
            'new_people_names': [],
            'new_people_emails': [],
            'new_people_affiliations': [],
            'new_people_addresses': [],
            'new_people_phones': [],
            'study_title': 'New title - test post edit',
            'study_alias': study_info['study_alias'],
            'publications_doi': '',
            'study_abstract': study_info['study_abstract'],
            'study_description': study_info['study_description'],
            'notes': '',
            'principal_investigator': study_info['principal_investigator'].id,
            'lab_person': study_info['lab_person'].id
        }

        response = self.post('/study/edit/1', post_data)
        self.assertEqual(response.code, 200)
        # Check that the study was updated
        self.assertTrue(check_count('qiita.study', study_count_before))
        self.assertEqual(study.title, 'New title - test post edit')
        self.assertEqual(study.publications, [])

        # check for failure
        old_title = post_data['study_title']
        post_data['study_title'] = 'My new title!'
        shared = User('*****@*****.**')
        study.unshare(shared)
        BaseHandler.get_current_user = Mock(return_value=shared)
        response = self.post('/study/edit/1', post_data)
        self.assertEqual(response.code, 403)
        # Check that the study wasn't updated
        self.assertEqual(study.title, old_title)

        # returning sharing
        study.share(shared)
Beispiel #17
0
def workflow_handler_post_req(user_id, dflt_params_id, req_params):
    """Creates a new workflow in the system

    Parameters
    ----------
    user_id : str
        The user creating the workflow
    dflt_params_id : int
        The default parameters to use for the first command of the workflow
    req_params : str
        JSON representations of the required parameters for the first
        command of the workflow

    Returns
    -------
    dict of objects
        A dictionary containing the commands information
        {'status': str,
         'message': str,
         'workflow_id': int}
    """
    dflt_params = DefaultParameters(dflt_params_id)
    req_params = loads(req_params)
    parameters = Parameters.from_default_params(dflt_params, req_params)
    wf = ProcessingWorkflow.from_scratch(User(user_id), parameters)
    # this is safe as we are creating the workflow for the first time and there
    # is only one node. Remember networkx doesn't assure order of nodes
    job = wf.graph.nodes()[0]
    inputs = [a.id for a in job.input_artifacts]
    job_cmd = job.command
    return {
        'status': 'success',
        'message': '',
        'workflow_id': wf.id,
        'job': {
            'id': job.id,
            'inputs': inputs,
            'label': job_cmd.name,
            'outputs': job_cmd.outputs
        }
    }
Beispiel #18
0
    def post(self):
        message = ""
        level = ""
        page = "lost_pass.html"
        user_id = None

        try:
            user = User(self.get_argument("email"))
        except QiitaDBUnknownIDError:
            message = "ERROR: Unknown user."
            level = "danger"
        else:
            user_id = user.id
            user.generate_reset_code()
            info = user.info
            try:
                # qiita_config.base_url doesn't have a / at the end, but the
                # qiita_config.portal_dir has it at the beginning but not at
                # the end. This constructs the correct URL
                url = qiita_config.base_url + qiita_config.portal_dir
                send_email(
                    user.id, "Qiita: Password Reset", "Please go to "
                    "the following URL to reset your password: \n"
                    "%s/auth/reset/%s  \nYou "
                    "have 30 minutes from the time you requested a "
                    "reset to change your password. After this period, "
                    "you will have to request another reset." %
                    (url, info["pass_reset_code"]))
                message = ("Check your email for the reset code.")
                level = "success"
                page = "index.html"
            except Exception as e:
                message = ("Unable to send email. Error has been registered. "
                           "Your password has not been reset.")
                level = "danger"
                LogEntry.create('Runtime',
                                "Unable to send forgot password "
                                "email: %s" % str(e),
                                info={'User': user.id})

        self.render(page, user=user_id, message=message, level=level)
Beispiel #19
0
    def setUp(self):
        # Create a sample template file
        self.st_contents = SAMPLE_TEMPLATE

        # create a new study to attach the sample template
        info = {
            "timeseries_type_id": 1,
            "metadata_complete": True,
            "mixs_compliant": True,
            "number_samples_collected": 4,
            "number_samples_promised": 4,
            "portal_type_id": 3,
            "study_alias": "TestStudy",
            "study_description": "Description of a test study",
            "study_abstract": "No abstract right now...",
            "emp_person_id": StudyPerson(2),
            "principal_investigator_id": StudyPerson(3),
            "lab_person_id": StudyPerson(1)
        }
        self.study = Study.create(User('*****@*****.**'),
                                  "Test study", [1], info)
Beispiel #20
0
    def test_artifact_summary_post_request(self):
        # No access
        obs = artifact_summary_post_request('*****@*****.**', 1)
        exp = {
            'status': 'error',
            'message': 'User does not have access to study'
        }
        self.assertEqual(obs, exp)

        # Returns already existing job
        job = ProcessingJob.create(
            User('*****@*****.**'),
            Parameters.load(Command(7), values_dict={'input_data': 2}))
        job._set_status('queued')
        obs = artifact_summary_post_request('*****@*****.**', 2)
        exp = {
            'status': 'success',
            'message': '',
            'job': [job.id, 'queued', None]
        }
        self.assertEqual(obs, exp)
Beispiel #21
0
    def test_get_no_access(self):
        # Create a new study belonging to the 'shared' user, so 'test' doesn't
        # have access
        info = {
            'timeseries_type_id': 1,
            'lab_person_id': None,
            'principal_investigator_id': 3,
            'metadata_complete': False,
            'mixs_compliant': True,
            'study_description': 'desc',
            'study_alias': 'alias',
            'study_abstract': 'abstract'
        }
        u = User('*****@*****.**')
        s = Study.create(u, 'test_study', efo=[1], info=info)
        self.assertEqual(s.shared_with, [])

        args = {'selected': '*****@*****.**', 'id': s.id}
        response = self.get('/study/sharing/', args)
        self.assertEqual(response.code, 403)
        self.assertEqual(s.shared_with, [])
Beispiel #22
0
    def test_get_analysis_jobs_handler(self):
        user = User('*****@*****.**')
        dflt_analysis = user.default_analysis
        dflt_analysis.add_samples({
            4: [
                '1.SKB8.640193', '1.SKD8.640184', '1.SKB7.640196',
                '1.SKM9.640192', '1.SKM4.640180'
            ]
        })
        new = Analysis.create(user,
                              "newAnalysis",
                              "A New Analysis",
                              from_default=True)
        response = self.get('/analysis/description/%s/jobs/' % new.id)
        self.assertEqual(response.code, 200)

        # There is only one job
        job_id = new.jobs[0].id
        obs = loads(response.body)
        exp = {job_id: {'status': 'queued', 'step': None, 'error': ""}}
        self.assertEqual(obs, exp)
Beispiel #23
0
 def test_call(self):
     obs_res, obs_meta = self.search(
         '(sample_type = ENVO:soil AND COMMON_NAME = "rhizosphere '
         'metagenome" ) AND NOT Description_duplicate includes Burmese',
         User("*****@*****.**"))
     exp_meta = ["COMMON_NAME", "Description_duplicate", "sample_type"]
     exp_res = {1:
                [['1.SKM4.640180', 'rhizosphere metagenome', 'Bucu Rhizo',
                  'ENVO:soil'],
                 ['1.SKM5.640177', 'rhizosphere metagenome', 'Bucu Rhizo',
                  'ENVO:soil'],
                 ['1.SKD4.640185', 'rhizosphere metagenome', 'Diesel Rhizo',
                  'ENVO:soil'],
                 ['1.SKD6.640190', 'rhizosphere metagenome', 'Diesel Rhizo',
                 'ENVO:soil'],
                 ['1.SKM6.640187', 'rhizosphere metagenome', 'Bucu Rhizo',
                  'ENVO:soil'],
                 ['1.SKD5.640186', 'rhizosphere metagenome', 'Diesel Rhizo',
                  'ENVO:soil']]}
     self.assertEqual(obs_res, exp_res)
     self.assertEqual(obs_meta, exp_meta)
Beispiel #24
0
    def test_workflow_handler_patch_req(self):
        # Create a new workflow so it is in construction
        exp_command = Command(1)
        json_str = (
            '{"input_data": 1, "max_barcode_errors": 1.5, '
            '"barcode_type": "golay_12", "max_bad_run_length": 3, '
            '"rev_comp": false, "phred_quality_threshold": 3, '
            '"rev_comp_barcode": false, "rev_comp_mapping_barcodes": false, '
            '"min_per_read_length_fraction": 0.75, "sequence_max_n": 0}')
        exp_params = Parameters.load(exp_command, json_str=json_str)
        exp_user = User('*****@*****.**')
        name = "Test processing workflow"

        # tests success
        wf = ProcessingWorkflow.from_scratch(
            exp_user, exp_params, name=name, force=True)

        graph = wf.graph
        nodes = graph.nodes()
        job_id = nodes[0].id
        value = {'dflt_params': 10,
                 'connections': {job_id: {'demultiplexed': 'input_data'}}}
        obs = workflow_handler_patch_req(
            'add', '/%s/' % wf.id, req_value=dumps(value))
        new_jobs = set(wf.graph.nodes()) - set(nodes)
        self.assertEqual(len(new_jobs), 1)
        new_job = new_jobs.pop()
        exp = {'status': 'success',
               'message': '',
               'job': {'id': new_job.id,
                       'inputs': [job_id],
                       'label': 'Pick closed-reference OTUs',
                       'outputs': [['OTU table', 'BIOM']]}}
        self.assertEqual(obs, exp)

        obs = workflow_handler_patch_req(
            'remove', '/%s/%s/' % (wf.id, new_job.id))
        exp = {'status': 'success', 'message': ''}
        jobs = set(wf.graph.nodes()) - set(nodes)
        self.assertEqual(jobs, set())
Beispiel #25
0
    def test_get_study_no_samples(self):
        info = {
            "timeseries_type_id": 1,
            "metadata_complete": True,
            "mixs_compliant": True,
            "study_alias": "FCM",
            "study_description": "DESC",
            "study_abstract": "ABS",
            "principal_investigator_id": StudyPerson(3),
            'first_contact': datetime(2015, 5, 19, 16, 10),
            'most_recent_contact': datetime(2015, 5, 19, 16, 11),
        }

        new_study = Study.create(User('*****@*****.**'),
                                 "Some New Study for test", info)

        exp = []
        response = self.get('/api/v1/study/%d/samples' % new_study.id,
                            headers=self.headers)
        self.assertEqual(response.code, 200)
        obs = json_decode(response.body)
        self.assertEqual(obs, exp)
Beispiel #26
0
    def test_delete_study_empty_study(self):
        info = {
            "timeseries_type_id": '1',
            "metadata_complete": 'true',
            "mixs_compliant": 'true',
            "study_alias": "FCM",
            "study_description": "Microbiome of people who eat nothing but "
            "fried chicken",
            "study_abstract": "Exploring how a high fat diet changes the "
            "gut microbiome",
            "principal_investigator_id": StudyPerson(3),
            "lab_person_id": StudyPerson(1)
        }
        new_study = Study.create(User('*****@*****.**'),
                                 "Fried Chicken Microbiome %s" % time(), info)
        job = self._create_job('delete_study', {'study': new_study.id})
        private_task(job.id)
        self.assertEqual(job.status, 'success')

        # making sure the study doesn't exist
        with self.assertRaises(QiitaDBUnknownIDError):
            Study(new_study.id)
Beispiel #27
0
 def test_set_info(self):
     """Set info in a study"""
     newinfo = {
         "timeseries_type_id": 2,
         "metadata_complete": False,
         "number_samples_collected": 28,
         "lab_person_id": StudyPerson(2),
         "vamps_id": 'MBE_111222',
         "first_contact": "June 11, 2014"
     }
     new = Study.create(
         User('*****@*****.**'), 'NOT Identification of the '
         'Microbiomes for Cannabis Soils', [1], self.info)
     self.infoexp.update(newinfo)
     new.info = newinfo
     # add missing table cols
     self.infoexp["funding"] = None
     self.infoexp["spatial_series"] = None
     self.infoexp["most_recent_contact"] = None
     self.infoexp["reprocess"] = False
     self.infoexp["lab_person_id"] = 2
     self.assertEqual(new.info, self.infoexp)
Beispiel #28
0
    def get(self):
        user = self.current_user
        analysis = Analysis(int(self.get_argument("aid")))
        # make sure user has access to the analysis
        userobj = User(user)
        check_analysis_access(userobj, analysis.id)

        # get the dictionaries of selected samples and data types
        selproc_data, selsamples = self._selected_parser(analysis)

        self.render('search_studies.html',
                    user=user,
                    aid=analysis.id,
                    selsamples=selsamples,
                    selproc_data=selproc_data,
                    counts={},
                    fullcounts={},
                    searchmsg="",
                    query="",
                    results={},
                    availmeta=SampleTemplate.metadata_headers() +
                    get_table_cols("study"))
Beispiel #29
0
def sample_template_delete_req(study_id, user_id):
    """Deletes the sample template attached to the study

    Parameters
    ----------
    study_id : int
        The current study object id
    user_id : str
        The current user object id

    Returns
    -------
    dict
        results dictonary in the format
        {'status': status,
         'message': msg}

    status can be success, warning, or error depending on result
    message has the warnings or errors
    """
    exists = _check_sample_template_exists(int(study_id))
    if exists['status'] != 'success':
        return exists
    access_error = check_access(int(study_id), user_id)
    if access_error:
        return access_error

    qiita_plugin = Software.from_name_and_version('Qiita', 'alpha')
    cmd = qiita_plugin.get_command('delete_sample_template')
    params = Parameters.load(cmd, values_dict={'study': int(study_id)})
    job = ProcessingJob.create(User(user_id), params)

    # Store the job id attaching it to the sample template id
    r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id,
                 dumps({'job_id': job.id}))

    job.submit()

    return {'status': 'success', 'message': ''}
Beispiel #30
0
 def post(self):
     error = ""
     try:
         user = User(self.get_argument("email"))
     except QiitaDBUnknownIDError:
         error = "ERROR: Unknown user."
     else:
         user.generate_reset_code()
         info = user.info
         try:
             send_email(
                 user, "QIITA: Password Reset", "Please go to the "
                 "following URL to reset your password: "******"http://qiita.colorado.edu/auth/reset/%s" %
                 info["pass_reset_code"])
             error = "Password reset. Check your email for the reset code."
         except Exception as e:
             error = "Unable to send email."
             LogEntry.create('Runtime',
                             "Unable to send forgot password "
                             "email" % str(e),
                             info={'User': user.id})
     self.render("lost_pass.html", user=None, error=error)