# Path: riboSeed/shared_methods.py
# def md5(fname, string=False):
#     """straight from quantumsoup
#     http://stackoverflow.com/questions/3431825/
#         generating-an-md5-checksum-of-a-file
#     updated 20160916 for strings; if true, fname can be a string
#     """
#     if string:
#         return hashlib.md5(fname.encode('utf-8')).hexdigest()
#     else:
#         hash_md5 = hashlib.md5()
#         with open(fname, "rb") as f:
#             for chunk in iter(lambda: f.read(4096), b""):
#                 hash_md5.update(chunk)
#             return hash_md5.hexdigest()
# 
# Path: riboSeed/riboSwap.py
# def remove_bad_contig(infile, outfile, bad_name,
#                       logger=None):
#     """uruk-hai voice: "Find the bad contig! Gah! Find the bad contig!"
#     loop through the input file, and write out if the bad name
#     isnt in the record id.
#     return a path to the output file, or raise an error if duplicates found
#     """
#     FOUND = False
#     with open(infile, "r") as incontigs:
#         with open(outfile, "a") as outcontigs:
#             for i in SeqIO.parse(incontigs, "fasta"):
#                 if bad_name in i.id:
#                     if FOUND:
#                         logger.error("mutiple contigs with that name found!")
#                         raise ValueError
#                     else:
#                         logger.info("found bad contig: %s; removing", i.id)
#                         FOUND = True
#                 else:
#                     SeqIO.write(i, outcontigs, "fasta")
#     if not FOUND:
#         logger.warning("No contig found matching the supplied name: %s",
#                        bad_name)
#     return(outfile)
# 
# def append_replacement_contigs(infile, outfile, name_list, logger=None):
#     """
#     loop through the input file (de novo), and write out to the de fere novo
#     fasta without the bad contig. if namelist isnt in the record id.
#     return a path to the output file, or raise an error if duplicates found
#     """
#     found_list = []  # this is used to check for dups late on
# 
#     with open(infile, "r") as de_novo:
#         with open(outfile, "a") as clean_de_fere:
#             for i in SeqIO.parse(de_novo, "fasta"):
#                 for name in name_list:
#                     if name not in i.id:
#                         pass
#                     else:
#                         if name in found_list:
#                             logger.error("mutiple contigs found with name %s!",
#                                          name)
#                             raise ValueError
#                         else:
#                             logger.info("appending %s to output file", i.id)
#                             i.id = str("SWAPPED_" + i.id)
#                             i.name, i.description = '', ''  # just change id
#                             SeqIO.write(i, clean_de_fere, "fasta")
#                         found_list.append(name)
#             clean_de_fere.write("\n")
#     if len(found_list) != len(name_list):
#         logger.error("Not all replacement contigs found!")
#         raise ValueError
#     return(outfile)


import sys
import logging
import shutil
import os
import unittest
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from argparse import Namespace
from unittest.mock import MagicMock, patch
from riboSeed.shared_methods import md5
from riboSeed.riboSwap import remove_bad_contig, append_replacement_contigs
        outfile = os.path.join(self.test_dir, "contigs_minus_NODE_3.fasta")
        with self.assertRaises(ValueError):
            remove_bad_contig(infile=self.bad_fasta,
                              outfile=outfile,
                              bad_name="NODE_",
                              logger=logger)

    def test_append_replacement_contigs(self):
        outfile = os.path.join(self.test_dir, "contigs_minus_NODE_3.fasta")
        remove_bad_contig(infile=self.bad_fasta,
                          # outfile=self.good_fasta,
                          outfile=outfile,
                          # bad_name="NODE_3_length_222_cov_5.70526",
                          bad_name="NODE_3_",
                          logger=logger)
        append_replacement_contigs(infile=self.good_fasta, outfile=outfile,
                                   name_list="NODE_4_:NODE_5_".split(":"),
                                   logger=logger)
        self.assertEqual(md5(outfile),
                         md5(os.path.join(self.ref_dir,
                                          "ref_swapped_contigs.fasta")))
        self.to_be_removed.append(outfile)

    def test_fail_append_replacement_contigs(self):
        outfile = os.path.join(self.test_dir, "contigs_minus_NODE_3.fasta")
        remove_bad_contig(infile=self.bad_fasta,
                          outfile=outfile,
                          bad_name="NODE_3_",
                          logger=logger)
        with self.assertRaises(ValueError):

# Path: riboSeed/shared_methods.py
# def md5(fname, string=False):
#     """straight from quantumsoup
#     http://stackoverflow.com/questions/3431825/
#         generating-an-md5-checksum-of-a-file
#     updated 20160916 for strings; if true, fname can be a string
#     """
#     if string:
#         return hashlib.md5(fname.encode('utf-8')).hexdigest()
#     else:
#         hash_md5 = hashlib.md5()
#         with open(fname, "rb") as f:
#             for chunk in iter(lambda: f.read(4096), b""):
#                 hash_md5.update(chunk)
#             return hash_md5.hexdigest()
# 
# Path: riboSeed/riboSwap.py
# def remove_bad_contig(infile, outfile, bad_name,
#                       logger=None):
#     """uruk-hai voice: "Find the bad contig! Gah! Find the bad contig!"
#     loop through the input file, and write out if the bad name
#     isnt in the record id.
#     return a path to the output file, or raise an error if duplicates found
#     """
#     FOUND = False
#     with open(infile, "r") as incontigs:
#         with open(outfile, "a") as outcontigs:
#             for i in SeqIO.parse(incontigs, "fasta"):
#                 if bad_name in i.id:
#                     if FOUND:
#                         logger.error("mutiple contigs with that name found!")
#                         raise ValueError
#                     else:
#                         logger.info("found bad contig: %s; removing", i.id)
#                         FOUND = True
#                 else:
#                     SeqIO.write(i, outcontigs, "fasta")
#     if not FOUND:
#         logger.warning("No contig found matching the supplied name: %s",
#                        bad_name)
#     return(outfile)
# 
# def append_replacement_contigs(infile, outfile, name_list, logger=None):
#     """
#     loop through the input file (de novo), and write out to the de fere novo
#     fasta without the bad contig. if namelist isnt in the record id.
#     return a path to the output file, or raise an error if duplicates found
#     """
#     found_list = []  # this is used to check for dups late on
# 
#     with open(infile, "r") as de_novo:
#         with open(outfile, "a") as clean_de_fere:
#             for i in SeqIO.parse(de_novo, "fasta"):
#                 for name in name_list:
#                     if name not in i.id:
#                         pass
#                     else:
#                         if name in found_list:
#                             logger.error("mutiple contigs found with name %s!",
#                                          name)
#                             raise ValueError
#                         else:
#                             logger.info("appending %s to output file", i.id)
#                             i.id = str("SWAPPED_" + i.id)
#                             i.name, i.description = '', ''  # just change id
#                             SeqIO.write(i, clean_de_fere, "fasta")
#                         found_list.append(name)
#             clean_de_fere.write("\n")
#     if len(found_list) != len(name_list):
#         logger.error("Not all replacement contigs found!")
#         raise ValueError
#     return(outfile)


# Path: tests/test_riboSwap.py
import sys
import logging
import shutil
import os
import unittest
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from argparse import Namespace
from unittest.mock import MagicMock, patch
from riboSeed.shared_methods import md5
from riboSeed.riboSwap import remove_bad_contig, append_replacement_contigs

        outfile = os.path.join(self.test_dir, "contigs_minus_NODE_3.fasta")
        with self.assertRaises(ValueError):
            remove_bad_contig(infile=self.bad_fasta,
                              outfile=outfile,
                              bad_name="NODE_",
                              logger=logger)

    def test_append_replacement_contigs(self):
        outfile = os.path.join(self.test_dir, "contigs_minus_NODE_3.fasta")
        remove_bad_contig(infile=self.bad_fasta,
                          # outfile=self.good_fasta,
                          outfile=outfile,
                          # bad_name="NODE_3_length_222_cov_5.70526",
                          bad_name="NODE_3_",
                          logger=logger)
        append_replacement_contigs(infile=self.good_fasta, outfile=outfile,
                                   name_list="NODE_4_:NODE_5_".split(":"),
                                   logger=logger)
        self.assertEqual(md5(outfile),
                         md5(os.path.join(self.ref_dir,
                                          "ref_swapped_contigs.fasta")))
        self.to_be_removed.append(outfile)

    def test_fail_append_replacement_contigs(self):
        outfile = os.path.join(self.test_dir, "contigs_minus_NODE_3.fasta")
        remove_bad_contig(infile=self.bad_fasta,
                          outfile=outfile,
                          bad_name="NODE_3_",
                          logger=logger)
        with self.assertRaises(ValueError):

            append_replacement_contigs(