def test_fullname(self):
     """Returns name of section along with common name."""
     ser = Section()
     assert ser.fullname is None
     ser.name = 'Dalmatian'
     assert ser.fullname == 'Dalmatian'
     ser.common_name = CommonName(name='Foxglove')
     assert ser.fullname == 'Dalmatian Foxglove'
Exemple #2
0
    def save_row_to_db(self, row, stream=sys.stdout):
        """Save a row from the Common Names sheet to the database.

        Args:
            row: The number of the row to save.
            stream: Optional IO stream to print messages to.

        Returns:
            bool: `True` if changes have been made, `False` if not.
        """
        cn_json = self.cell(row, self.cols['Common Name (JSON)']).value
        cn_dict = json.loads(cn_json)
        section = dbify(self.cell(row, self.cols['Section']).value)
        description = self.cell(row, self.cols['Description']).value

        print('-- BEGIN editing/creating Section \'{0}\' from row #{1}. '
              '--'.format(section, row), file=stream)
        edited = False
        cn = CommonName.get_or_create(name=dbify(cn_dict['Common Name']),
                                      index=dbify(cn_dict['Index']),
                                      stream=stream)
        sec = None
        if not cn.created:
            sec = Section.query\
                .filter(Section.name == section, Section.common_name_id == cn.id)\
                .one_or_none()
        if sec:
            print('The Section \'{0}\' has been loaded from the database.'
                  .format(sec.name), file=stream)
        else:
            edited = True
            sec = Section(name=section)
            sec.common_name = cn
            print('CommonName for the Section \'{0}\' set to: {1}'
                  .format(sec.name, cn.name), file=stream)
            db.session.add(sec)
            print('The Section \'{0}\' does not yet exist in the database, '
                  'so it has been created.'.format(sec.name), file=stream)
        if description != sec.description:
            edited = True
            if description:
                sec.description = description
                print('Description for the Section \'{0}\' set to: {1}'
                      .format(sec.name, sec.description), file=stream)
            else:
                sec.description = None
                print('Description for the Section \'{0}\' has been cleared.'
                      .format(sec.name), file=stream)
        if edited:
            db.session.flush()
            print('Changes to the Section \'{0}\' have been flushed to '
                  'the database.'.format(sec.name), file=stream)
        else:
            print('No changes were made to the Section \'{0}\'.'
                  .format(sec.name), file=stream)
        print('-- END editing/creating Section \'{0}\' from row #{1}. '
              '--'.format(sec.name, row), file=stream)
        return edited
 def test_validate_section_id(self, m_secq):
     """Raise error if selected sec is not in selected CN."""
     sec = Section(name="Five")
     sec.common_name_id = 1
     m_secq.return_value = sec
     self = mock.MagicMock()
     self.common_name_id.data = 2
     field = mock.MagicMock()
     with pytest.raises(ValidationError):
         EditCultivarForm.validate_section_id(self=self, field=field)
Exemple #4
0
 def test_add_one_with_description(self):
     """Set Description column's cell with Section desc."""
     wb = Workbook()
     ws = wb.active
     srws = SectionsWorksheet(ws)
     srws.setup()
     sr = Section(name='Polkadot', description='A bit spotty.')
     sr.common_name = CommonName(name='Foxglove')
     sr.common_name.index = Index(name='Perennial')
     srws.add_one(sr)
     assert srws.cell(
         2, srws.cols['Description']
     ).value == 'A bit spotty.'
 def test_set_selects(self, db):
     """Populate common_name select with ids from database."""
     cn1 = CommonName(name='Foxglove')
     cn2 = CommonName(name='Butterfly Weed')
     cn3 = CommonName(name='Tomato')
     sec = Section(name='Juicy')
     sec.common_name = cn1
     db.session.add_all([cn1, cn2, cn3])
     db.session.commit()
     form = EditSectionForm(obj=sec)
     form.set_selects()
     assert (cn1.id, cn1.name) in form.common_name_id.choices
     assert (cn2.id, cn2.name) in form.common_name_id.choices
     assert (cn3.id, cn3.name) in form.common_name_id.choices
Exemple #6
0
 def test_add_one_no_optionals(self):
     """Add a Section object to the Section worksheet."""
     messages = StringIO()
     wb = Workbook()
     ws = wb.active
     srws = SectionsWorksheet(ws)
     srws.setup()
     sr = Section(name='Polkadot')
     sr.common_name = CommonName(name='Foxglove')
     sr.common_name.index = Index(name='Perennial')
     srws.add_one(sr, stream=messages)
     assert srws.cell(
         2, srws.cols['Common Name (JSON)']
     ).value == json.dumps(sr.common_name.queryable_dict)
     assert srws.cell(2, srws.cols['Section']).value == 'Polkadot'
     assert srws.cell(2, srws.cols['Description']).value is None
     messages.seek(0)
     msgs = messages.read()
     assert ('Adding data from <Section "Polkadot Foxglove"> to row #2 '
             'of sections worksheet') in msgs
Exemple #7
0
def set_related_links():
    with open('/tmp/related_links.json', 'r', encoding='utf-8') as ifile:
        dicts = json.loads(ifile.read())
        print('Setting related links/grows with...')
        for d in dicts:
            cn = CommonName.from_slugs(
                d['source']['idx_slug'],
                d['source']['cn_slug']
            )
            if d['target']['anchor']:
                t = Cultivar.from_slugs(
                    d['target']['idx_slug'],
                    d['target']['cn_slug'],
                    d['target']['anchor']
                )
                if t:
                    cn.gw_cultivars.append(t)
                else:
                    t = Section.from_slugs(
                        d['target']['idx_slug'],
                        d['target']['cn_slug'],
                        d['target']['anchor']
                    )
                    if t:
                        cn.gw_sections.append(t)
                    else:
                        print(
                            'Could not find a Section or Cultivar with the '
                            'slug: "{}"'.format(d['target']['anchor'])
                        )
                        t = CommonName.from_slugs(
                            d['target']['idx_slug'],
                            d['target']['cn_slug']
                        )
                        cn.gw_common_names.append(t)
            else:
                t = CommonName.from_slugs(
                    d['target']['idx_slug'],
                    d['target']['cn_slug']
                )
                if t:
                    cn.gw_common_names.append(t)
                else:
                    print('Could not find gw for {}'.format(d))
            if t:
                print(
                    '"{}" grows with the {} "{}"'
                    .format(cn.name, t.__class__.__name__, t.name)
                )
        db.session.commit()
Exemple #8
0
def generate_sections(cn, l):
    for d in l:
        sec = Section.get_or_create(d['name'], cn)
        db.session.add(sec)
        sec.botanical_names = d['botanical_names']
        sec.subtitle = d['subtitle']
        sec.description = d['description']
        if d['thumbnail']:
            sec.thumbnail = download_image(d['thumbnail'])
        sec.cultivars = list(generate_cultivars(cn, d['cultivars']))
        sec.children = list(generate_sections(cn, d['subsections']))
        db.session.flush()
        sec.child_cultivars.reorder()
        sec.children.reorder()
        yield sec
Exemple #9
0
    def save_row_to_db(self, row, stream=sys.stdout):
        """Save a row from the Cultivars sheet to the database.

        Args:
            row: The number of the row to save.
            stream: Optional IO stream to print messages to.

        Returns:
            bool: `True` if changes have been made, `False` if not.
        """
        index = dbify(self.cell(row, self.cols['Index']).value)
        common_name = dbify(self.cell(row, self.cols['Common Name']).value)
        cultivar = dbify(self.cell(row, self.cols['Cultivar Name']).value)
        section = dbify(self.cell(row, self.cols['Section']).value)
        if not section:
            section = None
        botanical_name = self.cell(row, self.cols['Botanical Name']).value
        thumbnail = self.cell(row, self.cols['Thumbnail Filename']).value
        description = self.cell(row, self.cols['Description']).value
        synonyms = self.cell(row, self.cols['Synonyms']).value
        if not synonyms:
            synonyms = ''
        nus = self.cell(row, self.cols['New Until']).value
        if nus:
            new_until = datetime.datetime.strptime(nus, '%m/%d/%Y').date()
        else:
            new_until = None
        n_stk = self.cell(row, self.cols['In Stock']).value
        if n_stk and 'true' in n_stk.lower():
            in_stock = True
        else:
            in_stock = False
        act = self.cell(row, self.cols['Active']).value
        if act and 'true' in act.lower():
            active = True
        else:
            active = False
        vis = self.cell(row, self.cols['Visible']).value
        if vis and 'true' in vis.lower():
            visible = True
        else:
            visible = False

        print('-- BEGIN editing/creating Cultivar \'{0}\' from row #{1}. '
              '--'.format(cultivar + ' ' + common_name, row), file=stream)
        edited = False
        cv = Cultivar.get_or_create(name=cultivar,
                                    index=index,
                                    common_name=common_name,
                                    stream=stream)
        if cv.created:
            edited = True
            db.session.add(cv)
            if section:  # Section already exists if cv was not created.
                sec = Section.query\
                    .join(CommonName, CommonName.id == Section.common_name_id)\
                    .join(Index, Index.id == CommonName.index_id)\
                    .filter(Section.name == section,
                            CommonName.name == common_name,
                            Index.name == index)\
                    .one_or_none()
                if sec:
                    print('The Section \'{0}\' has been loaded from the '
                          'database.'.format(sec.name), file=stream)
                else:
                    sec = Section(name=section)
                    sec.common_name = cv.common_name
                    print('The Section \'{0}\' does not yet exist, so it has '
                          'been created.'.format(sec.name), file=stream)
                cv.section = sec
                print('Section for the Cultivar \'{0}\' set to: {1}'
                      .format(cv.fullname, sec.name), file=stream)
        if botanical_name:
            if not BotanicalName.validate(botanical_name):
                obn = botanical_name
                words = botanical_name.strip().split(' ')
                words[0] = words[0].capitalize()
                botanical_name = ' '.join(words)
                print('The BotanicalName \'{0}\' does not appear to be a '
                      'validly formatted botanical name. In an attempt to fix '
                      'it, it has been changed to: \'{1}\''
                      .format(obn, botanical_name), file=stream)
            bn = BotanicalName.query\
                .filter(BotanicalName.name == botanical_name)\
                .one_or_none()
            if bn and bn is not cv.botanical_name:
                print('The BotanicalName \'{0}\' has been loaded from the '
                      'database.'.format(bn.name), file=stream)
            elif not bn:
                bn = BotanicalName(name=botanical_name)
                bn.common_names.append(cv.common_name)
                print('The BotanicalName \'{0}\' does not yet exist, so it '
                      'has been created.'.format(bn.name), file=stream)
            if bn is not cv.botanical_name:
                edited = True
                cv.botanical_name = bn
                print('BotanicalName for the Cultivar \'{0}\' set to: {1}'
                      .format(cv.fullname, bn.name), file=stream)
        if thumbnail:
            if not cv.thumbnail or cv.thumbnail.filename != thumbnail:
                edited = True
                tn = Image.query\
                    .filter(Image.filename == thumbnail)\
                    .one_or_none()
                if tn:
                    print('The Image with the filename \'{0}\' has been '
                          'loaded from the database.'.format(tn.filename),
                          file=stream)
                else:
                    tn = Image(filename=thumbnail)
                    print('The Image with the filename \'{0}\' does not yet '
                          'exist in the database, so it has been created.'
                          .format(tn.filename), file=stream)
                cv.thumbnail = tn
                print('The Image with the filename \'{0}\' has been set as '
                      'the thumbnail for the Cultivar \'{1}\'.'
                      .format(tn.filename, cv.fullname), file=stream)
                if not tn.exists():
                    print('WARNING: The image file \'{0}\' set as the '
                          'thumbnail for the Cultivar \'{1}\' does not exist! '
                          'Please make sure you add the image file to the '
                          'images directory.'.format(tn.filename, cv.fullname),
                          file=stream)
        if description != cv.description:
            edited = True
            if description:
                cv.description = description
                print('Description for the Cultivar \'{0}\' set to: {1}'
                      .format(cv.fullname, cv.description), file=stream)
            else:
                cv.description = None
                print('Description for the Cultivar \'{0}\' has been cleared.'
                      .format(cv.fullname), file=stream)
        if synonyms != cv.synonyms_string:
            edited = True
            cv.synonyms_string = synonyms
            if synonyms:
                print('Synonyms for the Cultivar \'{0}\' set to: {1}'
                      .format(cv.fullname, cv.synonyms_string),
                      file=stream)
            else:
                print('Synonyms for the Cultivar \'{0}\' have been cleared.'
                      .format(cv.fullname), file=stream)
        if new_until != cv.new_until:
            edited = True
            if new_until:
                cv.new_until = new_until
                print('The Cultivar \'{0}\' has been set as new until {1}.'
                      .format(cv.fullname, cv.new_until.strftime('%m/%d/%Y')),
                      file=stream)
            else:
                cv.new_until = None
                print('The Cultivar \'{0}\' is no longer set as new.'
                      .format(cv.fullname), file=stream)
        if in_stock != cv.in_stock:
            edited = True
            cv.in_stock = in_stock
            if cv.in_stock:
                print('The Cultivar \'{0}\' is in stock.'.format(cv.fullname),
                      file=stream)
            else:
                print('The Cultivar \'{0}\' is out of stock.'
                      .format(cv.fullname), file=stream)
        if active != cv.active:
            edited = True
            cv.active = active
            if cv.active:
                print('The Cultivar \'{0}\' is active.'.format(cv.fullname),
                      file=stream)
            else:
                print('The Cultivar \'{0}\' is inactive.'.format(cv.fullname),
                      file=stream)
        if visible != cv.visible:
            edited = True
            cv.visible = visible
            if cv.visible:
                print('The Cultivar \'{0}\' will be shown on auto-generated '
                      'pages.'.format(cv.fullname), file=stream)
            else:
                print('The Cultivar \'{0}\' will not be shown on '
                      'auto-generated pages.'.format(cv.fullname), file=stream)
        if edited:
            db.session.flush()
            print('Changes to the Cultivar \'{0}\' have been flushed to '
                  'the database.'.format(cv.fullname), file=stream)
        else:
            print('No changes were made to the Cultivar \'{0}\'.'
                  .format(cv.fullname), file=stream)
        print('-- END editing/creating Cultivar \'{0}\' from row #{1}. '
              '--'.format(cv.fullname, row), file=stream)
        return edited
 def test_repr(self):
     """Return formatted string with full name."""
     sec = Section(name='Polkadot',
                   common_name=CommonName(name='Foxglove'))
     assert sec.__repr__() == '<Section "Polkadot Foxglove">'