def test_exists(self, mock_exists): """Call os.path.exists for path of image file.""" mock_exists.return_value = True image = Image() image.filename = 'hello.jpg' assert image.exists() mock_exists.assert_called_with(image.full_path)
def test_full_path(self): """Return the absolute file path for image name.""" image = Image() image.filename = 'hello.jpg' assert image.full_path ==\ os.path.join(current_app.config.get('IMAGES_FOLDER'), 'plants', image.filename)
def test_remove_cultivar_delete_images_deletes_images(self, mock_delete, app, db): """Delete images and thumbnail if delete_images is checked.""" cultivar = foxy_cultivar() img = Image() img.filename = "foxee.jpg" thumb = Image() thumb.filename = "foxy.jpg" cultivar.images.append(img) cultivar.thumbnail = thumb db.session.add_all([cultivar, img, thumb]) db.session.commit() with app.test_client() as tc: tc.post( url_for("seeds.remove_cultivar", cv_id=cultivar.id), data=dict(verify_removal=True, delete_images=True), follow_redirects=True, ) assert Image.query.count() == 0 assert mock_delete.called
def download_image(url): relname = Path(*url.replace('//', '').split('/')[1:]) fullname = Path(STATIC, relname.parent, secure_filename(relname.name)) if fullname.exists(): print('Image {} already exists, skipping download.'.format(fullname)) else: print('Downloading {} and saving to "{}"...'.format(url, fullname)) img_file = requests.get(url) if img_file.status_code == 200: fullname.parent.mkdir(parents=True, exist_ok=True) with fullname.open('wb') as ofile: ofile.write(img_file.content) else: try: img_file.raise_for_status() except requests.HTTPError as e: with open('/tmp/404.log', 'a', encoding='utf-8') as ofile: ofile.write('{}\n'.format(e)) img = Image.get_or_create(filename=str(relname)) return img
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_delete_file(self, mock_remove): """Delete image file using os.remove.""" image = Image() image.filename = 'hello.jpg' image.delete_file() mock_remove.assert_called_with(image.full_path)
def test_repr(self): """Return string representing Image.""" image = Image(filename='hello.jpg') assert image.__repr__() == '<Image filename: "hello.jpg">'