예제 #1
0
    def test_card_set_parser_no_id(self):
        """Test physical card set reading for new card sets"""
        self.maxDiff = None
        aAddedPhysCards = get_phys_cards()
        # We have a physical card list, so create some physical card sets

        # Check input

        oParser = PhysicalCardSetParser()

        # Repeat set 1 so the numbers match up
        oHolder = CardSetHolder()
        oParser.parse(StringIO(PCS_EXAMPLE_1), oHolder)
        oHolder.create_pcs()

        oHolder = CardSetHolder()
        oParser.parse(StringIO(PCS_EXAMPLE_2_NO_ID), oHolder)
        oHolder.create_pcs()

        oHolder = CardSetHolder()
        oParser.parse(StringIO(PCS_EXAMPLE_3_NO_ID), oHolder)
        oHolder.create_pcs()

        oPhysCardSet2 = IPhysicalCardSet(CARD_SET_NAMES[1])
        oPhysCardSet3 = IPhysicalCardSet(CARD_SET_NAMES[2])

        self.assertEqual(len(oPhysCardSet2.cards), 8)
        self.assertEqual(len(oPhysCardSet3.cards), 7)

        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[7].id).count(), 2)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[4].id).count(), 3)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[0].id).count(), 1)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[1].id).count(), 1)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[6].id).count(), 3)
        # Aaron's Feeding razor
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[14].id).count(), 0)
        # Inez
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[12].id).count(), 0)

        self.assertEqual(oPhysCardSet2.annotations, None)
        self.assertEqual(oPhysCardSet3.annotations, 'Some annotations')

        self.assertEqual(oPhysCardSet2.comment, 'A test comment')
        self.assertEqual(oPhysCardSet3.comment, 'A formatted test comment\n'
                         'A second line')
예제 #2
0
    def test_abstract_cs_parser(self):
        """Test abstract card set parser"""
        # Support for everything except reading has been removed.
        # It is expected that reading in an ACS will create an
        # equivalent PCS.
        self.maxDiff = None

        oParser = AbstractCardSetParser()

        sTempFileName = self._create_tmp_file()
        fOut = open(sTempFileName, 'w')
        fOut.write(ACS_EXAMPLE_1)
        fOut.close()

        oHolder = CardSetHolder()
        oParser.parse(StringIO(ACS_EXAMPLE_2), oHolder)
        oHolder.create_pcs()
        fIn = open(sTempFileName, 'r')
        oHolder = CardSetHolder()
        oParser.parse(fIn, oHolder)
        oHolder.create_pcs()
        fIn.close()

        oCardSet1 = IPhysicalCardSet("(ACS) " + CARD_SET_NAMES[0])
        oCardSet2 = IPhysicalCardSet("(ACS) " + CARD_SET_NAMES[1])

        oPhysCard0 = make_card(ABSTRACT_CARDS[0][0], None)
        oPhysCard2 = make_card(ABSTRACT_CARDS[2][0], None)

        self.assertEqual(len(oCardSet1.cards), 5)
        self.assertEqual(len(oCardSet2.cards), 9)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=oPhysCard0.id).count(), 3)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=oPhysCard2.id).count(), 2)

        PhysicalCardSet.delete(oCardSet1.id)
        oFile = AbstractCardSetXmlFile()
        self.assertRaises(IOError, oFile.read)
        oFile = AbstractCardSetXmlFile(sTempFileName)
        oFile.read()
        oCardSet1 = IPhysicalCardSet("(ACS) Test Set 1")
        self.assertEqual(len(oCardSet1.cards), 5)
        oFile.delete()
        self.assertFalse(os.path.exists(sTempFileName))
        self.assertRaises(RuntimeError, oFile.write, '(ACS) Test Set 1')

        oHolder = CardSetHolder()
        self.assertRaises(IOError, oParser.parse,
                          StringIO('<caarrd>%s</caarrd>' % ACS_EXAMPLE_1),
                          oHolder)
예제 #3
0
    def test_physical(self):
        """Test physical card handling"""
        # test IO
        self.maxDiff = None
        sExample = make_example_pcxml()
        oParser = PhysicalCardParser()
        oHolder = CardSetHolder()
        oParser.parse(StringIO(sExample), oHolder)
        oHolder.create_pcs()

        oMyCollection = IPhysicalCardSet("My Collection")
        self.assertEqual(len(oMyCollection.cards), 1)
        PhysicalCardSet.delete(oMyCollection.id)

        sTempFileName = self._create_tmp_file()
        fOut = open(sTempFileName, 'w')
        fOut.write(sExample)
        fOut.close()

        fIn = open(sTempFileName, 'r')
        oHolder = CardSetHolder()
        oParser.parse(fIn, oHolder)
        fIn.close()
        oHolder.create_pcs()

        # Test incorrect input
        oHolder = CardSetHolder()
        self.assertRaises(
            IOError, oParser.parse,
            StringIO('<ccaardd sutekh_xml_version="1.0"><card'
                     ' count="1" expansion="None Specified"'
                     ' id="12" name="Abbot" /></ccaardd>'), oHolder)
        self.assertRaises(
            IOError, oParser.parse,
            StringIO('<cards sutekh_xml_version="5.0"><card'
                     ' count="1" expansion="None Specified"'
                     ' id="12" name="Abbot" /></cards>'), oHolder)

        # Check read results
        oMyCollection = IPhysicalCardSet("My Collection")
        self.assertEqual(len(oMyCollection.cards), 1)
        PhysicalCardSet.delete(oMyCollection.id)

        oFile = PhysicalCardXmlFile(sTempFileName)
        oFile.read()
        oMyCollection = IPhysicalCardSet("My Collection")
        self.assertEqual(len(oMyCollection.cards), 1)
        oFile.delete()
        self.assertFalse(os.path.exists(sTempFileName))
        self.assertRaises(RuntimeError, oFile.write)
예제 #4
0
    def test_roundtrip(self):
        """Test that we round trip one of the card sets from the
           writer successfully"""
        # We rely on the writer tests to ensure that the strings
        # are the output of the card sets
        self.maxDiff = None
        oParser = PhysicalCardSetParser()
        for sData, fCardSet, sName in [
            (EXPECTED_1, make_set_1, CARD_SET_NAMES[0]),
            (EXPECTED_4, make_set_3, CARD_SET_NAMES[2])
        ]:
            oOrig = fCardSet()
            # Make sure we don't clash
            oOrig.name = 'Original ' + oOrig.name
            oOrig.syncUpdate()
            oHolder = CardSetHolder()
            oParser.parse(StringIO(sData), oHolder)
            oHolder.create_pcs()
            oRead = IPhysicalCardSet(sName)
            self.assertEqual(oRead.author, oOrig.author)
            self.assertEqual(oRead.comment, oOrig.comment)

            # Check that the card sets have the same cards
            self.assertEqual(len(oRead.cards), len(oOrig.cards))
            # pylint: disable=not-an-iterable
            # SQLObject confuses pylint here
            for oCard in oOrig.cards:
                self.assertTrue(
                    oCard in oRead.cards, "%s and %s differ on card %s" %
                    (oRead.name, oOrig.name, oCard.abstractCard.name))
    def test_read_single(self):
        """Check read_single_works"""
        self.maxDiff = None
        sTempFileName = self._create_tmp_file()
        oZipFile = ZipFileWrapper(sTempFileName)
        aPhysCards = get_phys_cards()

        oMyCollection = PhysicalCardSet(name='My Collection')

        for oCard in aPhysCards:
            # pylint: disable=no-member
            # SQLObject confuses pylint
            oMyCollection.addPhysicalCard(oCard.id)
            oMyCollection.syncUpdate()

        oHandler = SutekhCountLogHandler()
        oZipFile.do_dump_all_to_zip(oHandler)

        oHolder = oZipFile.read_single_card_set('My_Collection.xml')
        self.assertEqual(oHolder.name, oMyCollection.name)

        delete_physical_card_set(oMyCollection.name)
        oHolder.create_pcs()
        oMyCollection = IPhysicalCardSet('My Collection')

        self.assertEqual(
            sorted([x.abstractCard.name for x in oMyCollection.cards]),
            sorted([x.abstractCard.name for x in aPhysCards]))
예제 #6
0
 def _make_cs(self, _oButton, oDlg):
     """Create a card set with the given cards"""
     # pylint: disable=no-member
     # SQLObject confuses pylint
     oView = oDlg.get_cur_widget().get_child()
     aCards = oView.get_selected_cards()
     if not aCards:
         do_complaint_error("No cards selected for card set.")
         return
     sCSName = create_card_set(self.parent)
     if sCSName:
         oCardSet = IPhysicalCardSet(sCSName)
         for oCard in aCards:
             # We add with unknown expansion
             # pylint: disable=no-member
             # SQLObject confuses pylint
             oCardSet.addPhysicalCard(IPhysicalCard((oCard, None)))
         self._open_cs(sCSName, True)
    def test_physical_card_set_writer(self):
        """Test physical card set writing"""
        self.maxDiff = None
        # pylint: disable=too-many-statements, too-many-locals
        # Want a long, sequential test case to minimise
        # repeated setups, so it has lots of lines + variables
        # We have a physical card list, so create some physical card sets
        oPhysCardSet1 = make_set_1()

        # Check output

        oWriter = PhysicalCardSetWriter()
        oFile = StringIO()
        oWriter.write(oFile, CardSetWrapper(oPhysCardSet1))
        sWriterXML = oFile.getvalue()
        oFile.close()
        self._compare_xml_strings(sWriterXML, EXPECTED_1)

        oPCS = IPhysicalCardSet(CARD_SET_NAMES[0])
        sData = self._round_trip_obj(oWriter, CardSetWrapper(oPCS))
        self._compare_xml_strings(sData, sWriterXML)
        self._compare_xml_strings(sData, EXPECTED_1)

        oPhysCardSet2 = make_set_2()

        oFile = StringIO()
        oWriter.write(oFile, CardSetWrapper(oPhysCardSet2))
        sWriterXML = oFile.getvalue()
        oFile.close()
        self._compare_xml_strings(sWriterXML, EXPECTED_2)

        sTempFileName = self._create_tmp_file()
        oFileXML = PhysicalCardSetXmlFile(sTempFileName)
        oFileXML.write(CARD_SET_NAMES[1])
        fIn = open(sTempFileName, 'r')
        sData = fIn.read()
        self._compare_xml_strings(sData, EXPECTED_2)

        # Unset the author
        oPhysCardSet2.author = None
        oFile = StringIO()
        oWriter.write(oFile, CardSetWrapper(oPhysCardSet2))
        sWriterXML = oFile.getvalue()
        oFile.close()
        self._compare_xml_strings(sWriterXML, EXPECTED_3)

        # Test with more unicode stuff
        oWriter = PhysicalCardSetWriter()

        oPhysCardSet3 = make_set_3()
        oFile = StringIO()
        oWriter.write(oFile, CardSetWrapper(oPhysCardSet3))
        sWriterXML = oFile.getvalue()
        oFile.close()
        self._compare_xml_strings(sWriterXML, EXPECTED_4)
예제 #8
0
def find_holder(aHolders):
    """Returns the first of the given holders that exists in the database,
       or None if all are missing."""
    for sCandidate in aHolders:
        try:
            oHolder = IPhysicalCardSet(sCandidate)
            return oHolder
        except SQLObjectNotFound:
            # We silence the error and move on to the next candidate
            pass
    return None
    def test_old_format(self):
        """Test that an old zip file loads correctly"""
        self.maxDiff = None
        # Create a test zipfile with old data
        sPhysicalCards = make_example_pcxml()

        oHandler = SutekhCountLogHandler()
        sTempFileName = self._create_tmp_file()
        oZipFile = zipfile.ZipFile(sTempFileName, 'w')
        oZipFile.writestr('PhysicalCardList.xml', sPhysicalCards)
        oZipFile.writestr('acs_set_1.xml', ACS_EXAMPLE_1)
        oZipFile.writestr('acs_set_2.xml', ACS_EXAMPLE_2)
        oZipFile.writestr('pcs_set_2.xml', PCS_EXAMPLE_1)
        oZipFile.close()

        # Check it loads correctly
        oZipWrapper = ZipFileWrapper(sTempFileName)
        oZipWrapper.do_restore_from_zip(oLogHandler=oHandler)
        self.assertEqual(oHandler.fTot, 4)

        oMyCollection = IPhysicalCardSet("My Collection")
        self.assertEqual(len(oMyCollection.cards), 1)

        oPhysCardSet1 = IPhysicalCardSet('Test Set 1')

        self.assertEqual(oPhysCardSet1.parent.id, oMyCollection.id)

        self.assertEqual(len(oPhysCardSet1.cards), 5)

        oACSCardSet1 = IPhysicalCardSet("(ACS) Test Set 1")
        oACSCardSet2 = IPhysicalCardSet("(ACS) Test Set 2")

        self.assertEqual(len(oACSCardSet1.cards), 5)
        self.assertEqual(len(oACSCardSet2.cards), 9)

        self.assertEqual(oACSCardSet1.parent, None)
        self.assertEqual(oACSCardSet2.parent, None)
예제 #10
0
 def write(self, sPCSName):
     """Write the given card set to the file"""
     oWriter = PhysicalCardSetWriter()
     if self.sXmlFile is None:
         sFileName = safe_filename(sPCSName) + '.xml'
     else:
         sFileName = self.sXmlFile
     fOut = open(sFileName, 'w')
     try:
         oPCS = IPhysicalCardSet(sPCSName)
     except SQLObjectNotFound as oExp:
         raise IOError(f'No card set named {sPCSName}') from oExp
     oHolder = CardSetWrapper(oPCS)
     oWriter.write(fOut, oHolder)
     fOut.close()
     return sFileName
예제 #11
0
    def _get_decks_to_download(self, aUrls, aDates, aHashes):
        """Check for any decks we need to download."""
        aToUnzip = []
        aToReplace = []

        for sUrl, sDate, sHash in zip(aUrls, aDates, aHashes):
            if not sUrl:
                return False, False
            # Check if we need to download this url
            # This is a bit crude, but works because we control the format
            sZipName = sUrl.split('/')[-1]
            sTWDA = sZipName.replace('Sutekh_', '').replace('.zip', '')
            # Drop any suffix to the TWDA name
            sTWDA = sTWDA[:9].replace('_', ' ')
            try:
                oHolder = IPhysicalCardSet(sTWDA)
            except SQLObjectNotFound:
                # New TWDA holder, so add it to the list
                aToUnzip.append((sUrl, sTWDA, sHash))
                continue
            # Existing TWDA entry, so check dates
            try:
                oUrlDate = datetime.datetime.strptime(sDate, '%Y-%m-%d')
            except ValueError:
                oUrlDate = None
            sTWDUpdated = "Date Updated:"
            oTWDDate = None
            for sLine in oHolder.annotations.splitlines():
                if sLine.startswith(sTWDUpdated):
                    sTWDDate = sLine.split(sTWDUpdated)[1][1:11]
                    try:
                        oTWDDate = datetime.datetime.strptime(sTWDDate,
                                                              '%Y-%m-%d')
                    except ValueError:
                        pass
            if oTWDDate is None or oUrlDate is None:
                # Unable to extract the dates correctly, so we treat this as
                # something to replace
                aToUnzip.append((sUrl, sTWDA, sHash))
                aToReplace.append(sTWDA)
            elif oTWDDate < oUrlDate:
                # Url is newer, so we replace
                aToUnzip.append((sUrl, sTWDA, sHash))
                aToReplace.append(sTWDA)
        return aToUnzip, aToReplace
예제 #12
0
    def test_card_set_parser_no_author(self):
        """Test physical card set reading for card sets without an author"""
        self.maxDiff = None
        oParser = PhysicalCardSetParser()

        oHolder = CardSetHolder()
        oParser.parse(StringIO(PCS_EXAMPLE_NO_AUTH), oHolder)
        oHolder.create_pcs()

        oPhysCardSet3 = IPhysicalCardSet(CARD_SET_NAMES[2])
        self.assertEqual(len(oPhysCardSet3.cards), 7)

        self.assertEqual(oPhysCardSet3.annotations, 'Some annotations')

        self.assertEqual(oPhysCardSet3.comment, 'A formatted test comment\n'
                         'A second line')

        # This test is a bit funky, as we may get either None or ''
        # depending on sqlobject version,
        self.assertTrue(oPhysCardSet3.author in (None, ''))
예제 #13
0
    def test_card_set_parser_ver1_4(self):
        """Test physical card set reading for a version 1.4 card set"""
        self.maxDiff = None
        oParser = PhysicalCardSetParser()

        oHolder = CardSetHolder()
        oParser.parse(StringIO(PCS_EXAMPLE_VER_1_4), oHolder)
        oHolder.create_pcs()

        oPhysCardSet14 = IPhysicalCardSet("Test Set 1.4")
        self.assertEqual(len(oPhysCardSet14.cards), 34)

        self.assertEqual(oPhysCardSet14.comment, 'A test comment')

        oOrig = make_set_1()
        oOrig.name = 'Original for 1.4 test'
        # pylint: disable=not-an-iterable
        # SQLObject confuses pylint here
        for oCard in oOrig.cards:
            self.assertTrue(
                oCard in oPhysCardSet14.cards, "%s and %s differ on card %s" %
                (oPhysCardSet14.name, oOrig.name, oCard.abstractCard.name))
예제 #14
0
    def test_physical_card_set_parser(self):
        """Test physical card set reading"""
        self.maxDiff = None
        # pylint: disable=too-many-statements, too-many-locals
        # Want a long, sequential test case to minimise
        # repeated setups, so it has lots of lines + variables
        aAddedPhysCards = get_phys_cards()
        # We have a physical card list, so create some physical card sets

        # Check input

        oParser = PhysicalCardSetParser()

        oHolder = CardSetHolder()
        oParser.parse(StringIO(PCS_EXAMPLE_1), oHolder)
        oHolder.create_pcs()

        sTempFileName = self._create_tmp_file()
        fIn = open(sTempFileName, 'w')
        fIn.write(PCS_EXAMPLE_2)
        fIn.close()
        fIn = open(sTempFileName, 'r')
        oHolder = CardSetHolder()
        oParser.parse(fIn, oHolder)
        oHolder.create_pcs()
        fIn.close()

        oHolder = CardSetHolder()
        oParser.parse(StringIO(PCS_EXAMPLE_3), oHolder)
        oHolder.create_pcs()

        oPhysCardSet1 = IPhysicalCardSet(CARD_SET_NAMES[0])
        oPhysCardSet2 = IPhysicalCardSet(CARD_SET_NAMES[1])
        oPhysCardSet3 = IPhysicalCardSet(CARD_SET_NAMES[2])

        self.assertEqual(len(oPhysCardSet1.cards), 5)
        self.assertEqual(len(oPhysCardSet2.cards), 8)
        self.assertEqual(len(oPhysCardSet3.cards), 7)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[0].id).count(), 1)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[7].id).count(), 2)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[4].id).count(), 3)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[1].id).count(), 1)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[6].id).count(), 3)
        # Aaron's Feeding razor
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[14].id).count(), 0)
        # Inez
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[12].id).count(), 0)

        PhysicalCardSet.delete(oPhysCardSet2.id)
        oFile = PhysicalCardSetXmlFile()
        self.assertRaises(IOError, oFile.read)
        oFile = PhysicalCardSetXmlFile(sTempFileName)
        oFile.read()
        oPhysCardSet2 = IPhysicalCardSet("Test Set 2")
        self.assertEqual(len(oPhysCardSet2.cards), 8)
        oFile.delete()
        self.assertFalse(os.path.exists(sTempFileName))
        oFile.write('Test Set 2')
        PhysicalCardSet.delete(oPhysCardSet2.id)
        self.assertTrue(os.path.exists(sTempFileName))
        oFile.read()
        oPhysCardSet2 = IPhysicalCardSet("Test Set 2")
        self.assertEqual(len(oPhysCardSet2.cards), 8)

        self.assertEqual(oPhysCardSet2.annotations, None)
        self.assertEqual(oPhysCardSet3.annotations, 'Some annotations')

        self.assertEqual(oPhysCardSet2.comment, 'A test comment')
        self.assertEqual(oPhysCardSet3.comment, 'A formatted test comment\n'
                         'A second line')

        oHolder = CardSetHolder()
        self.assertRaises(IOError, oParser.parse,
                          StringIO('<caards></caards>'), oHolder)
예제 #15
0
def main_with_args(aTheArgs):
    """
    Main function: Loop through the options and process the database
    accordingly.
    """
    # Turn off some pylint refactoring warnings
    # pylint: disable=too-many-statements, too-many-branches
    # pylint: disable=too-many-return-statements, too-many-locals
    oOptParser, (oOpts, aArgs) = parse_options(aTheArgs)
    sPrefsDir = prefs_dir(SutekhInfo.NAME)

    oLogHandler = StreamHandler(sys.stdout)

    if len(aArgs) != 1:
        oOptParser.print_help()
        return 1

    if oOpts.db is None:
        ensure_dir_exists(sPrefsDir)
        oOpts.db = sqlite_uri(os.path.join(sPrefsDir, "sutekh.db"))

    bDoCardListChecks = False

    oConn = connectionForURI(oOpts.db)
    sqlhub.processConnection = oConn

    if oOpts.sql_debug:
        oConn.debug = True

    if not oConn.tableExists('abstract_card'):
        if not oOpts.refresh_tables:
            print("Database has not been created.")
            return 1
    else:
        try:
            _oCard = IAbstractCard('Ossian')
        except SQLObjectNotFound:
            if not oOpts.fetch and oOpts.ww_file is None:
                print("Database is missing cards - please import the cardlist")
                return 1

    # Only log critical messages by default
    setup_logging(oOpts.verbose)

    if oOpts.reload:
        if not oOpts.refresh_tables:
            print("reload should be called with --refresh-tables")
            return 1
        sTempdir = gen_temp_dir()
        (fTemp, sReloadZipName) = \
            tempfile.mkstemp('.zip', 'sutekh', sTempdir)
        os.close(fTemp)
        oZipFile = ZipFileWrapper(sReloadZipName)
        oZipFile.do_dump_all_to_zip(oLogHandler)
        # We dump the databases here
        # We will reload them later

    if oOpts.refresh_ruling_tables:
        if not refresh_tables([Ruling], sqlhub.processConnection):
            print("refresh failed")
            return 1

    if oOpts.refresh_tables:
        if not refresh_tables(TABLE_LIST, sqlhub.processConnection):
            print("refresh failed")
            return 1

    if oOpts.refresh_physical_card_tables:
        if not refresh_tables(PHYSICAL_LIST, sqlhub.processConnection):
            print("refresh failed")
            return 1

    if oOpts.lookup_file is not None:
        read_lookup_data(EncodedFile(oOpts.lookup_file), oLogHandler)

    if oOpts.ww_file is not None:
        read_white_wolf_list(EncodedFile(oOpts.ww_file), oLogHandler)
        bDoCardListChecks = True

    if oOpts.extra_file is not None:
        read_white_wolf_list(EncodedFile(oOpts.extra_file), oLogHandler)
        bDoCardListChecks = True

    if oOpts.exp_data_file is not None:
        read_exp_info_file(EncodedFile(oOpts.exp_data_file), oLogHandler)

    if oOpts.ruling_file is not None:
        read_rulings(EncodedFile(oOpts.ruling_file), oLogHandler)

    if oOpts.fetch:
        read_lookup_data(EncodedFile(LOOKUP_DATA_URL, True), oLogHandler)
        read_white_wolf_list(EncodedFile(WW_CARDLIST_URL, True), oLogHandler)
        read_rulings(EncodedFile(WW_RULINGS_URL, True), oLogHandler)
        read_white_wolf_list(EncodedFile(EXTRA_CARD_URL, True), oLogHandler)
        read_exp_info_file(EncodedFile(EXP_DATA_URL, True), oLogHandler)
        bDoCardListChecks = True

    if bDoCardListChecks:
        # Run the consistency checks on the database
        for oAbsCard in AbstractCard.select():
            aMessages = do_card_checks(oAbsCard)
            if aMessages:
                print('\n'.join(aMessages))

    if oOpts.upgrade_db:
        oDBUpgrade = DBUpgradeManager()
        oDBUpgrade.attempt_database_upgrade(oLogHandler)

    if oOpts.save_all_css and oOpts.save_cs is not None:
        print("Can't use --save-cs and --save-all-cs Simulatenously")
        return 1

    # initialise the caches, so adapters, etc work for reading / writing
    # card sets
    make_adapter_caches()

    if oOpts.read_physical_cards_from is not None:
        oFile = PhysicalCardXmlFile(oOpts.read_physical_cards_from)
        oFile.read()

    if oOpts.save_all_css:
        write_all_pcs()

    if oOpts.dump_zip_name is not None:
        oZipFile = ZipFileWrapper(oOpts.dump_zip_name)
        oZipFile.do_dump_all_to_zip(oLogHandler)

    if oOpts.restore_zip_name is not None:
        oZipFile = ZipFileWrapper(oOpts.restore_zip_name)
        oZipFile.do_restore_from_zip(oLogHandler=oLogHandler)

    if oOpts.save_cs is not None:
        oFile = PhysicalCardSetXmlFile(oOpts.cs_filename)
        oFile.write(oOpts.save_cs)

    if oOpts.print_cs is not None:
        try:
            oCS = IPhysicalCardSet(oOpts.print_cs)
            fPrint = StringIO()
            oPrinter = WriteArdbText()
            oPrinter.write(fPrint, CardSetWrapper(oCS))
            print(fPrint.getvalue())
        except SQLObjectNotFound:
            print('Unable to load card set', oOpts.print_cs)
            return 1

    if oOpts.list_cs:
        if not print_card_list(oOpts.limit_list):
            return 1
    elif oOpts.limit_list is not None:
        print("Can't use limit-list-to without list-cs")
        return 1

    if oOpts.filter_string is not None:
        dResults = run_filter(oOpts.filter_string, oOpts.filter_cs)
        print_card_filter_list(dResults, print_card_details,
                               oOpts.filter_detailed)

    if oOpts.print_card is not None:
        if not do_print_card(oOpts.print_card, print_card_details):
            return 1

    if oOpts.read_cs is not None:
        oFile = PhysicalCardSetXmlFile(oOpts.read_cs)
        oFile.read()

    if oOpts.read_acs is not None:
        oFile = AbstractCardSetXmlFile(oOpts.read_acs)
        oFile.read()

    if oOpts.reload:
        oZipFile = ZipFileWrapper(sReloadZipName)
        oZipFile.do_restore_from_zip(oLogHandler=oLogHandler)
        os.remove(sReloadZipName)
        os.rmdir(sTempdir)

    if oOpts.upgrade_db and oOpts.refresh_tables:
        print("Can't use --upgrade-db and --refresh-tables simulatenously")
        return 1

    return 0
    def test_zip_file(self):
        """Test zip file handling"""
        self.maxDiff = None
        # pylint: disable=too-many-statements
        # Want a single test case to avoid re-initialising the database
        sTempFileName = self._create_tmp_file()
        oZipFile = ZipFileWrapper(sTempFileName)
        aPhysCards = get_phys_cards()

        oMyCollection = PhysicalCardSet(name='My Collection')

        for oCard in aPhysCards:
            # pylint: disable=no-member
            # SQLObject confuses pylint
            oMyCollection.addPhysicalCard(oCard.id)
            oMyCollection.syncUpdate()

        oPhysCardSet1 = PhysicalCardSet(name=CARD_SET_NAMES[0],
                                        parent=oMyCollection)
        oPhysCardSet1.comment = 'A test comment'
        oPhysCardSet1.author = 'A test author'

        self.assertNotEqual(oPhysCardSet1.parent, None)
        self.assertEqual(oPhysCardSet1.parent.id, oMyCollection.id)

        for iLoop in range(5):
            # pylint: disable=no-member
            # SQLObject confuses pylint
            oPhysCardSet1.addPhysicalCard(aPhysCards[iLoop].id)
            oPhysCardSet1.syncUpdate()
            if iLoop > 3:
                # Add a duplicate
                oPhysCardSet1.addPhysicalCard(aPhysCards[iLoop].id)
                oPhysCardSet1.syncUpdate()

        oPhysCardSet2 = PhysicalCardSet(name=CARD_SET_NAMES[1])
        oPhysCardSet2.comment = 'Test 2 comment'
        oPhysCardSet2.author = 'A different author'

        for iLoop in range(2, 7):
            # pylint: disable=no-member
            # SQLObject confuses pylint
            oPhysCardSet2.addPhysicalCard(aPhysCards[iLoop].id)
            oPhysCardSet2.syncUpdate()

        oHandler = SutekhCountLogHandler()
        oZipFile.do_dump_all_to_zip(oHandler)
        self.assertEqual(oHandler.fTot, 3)
        dEntries = oZipFile.get_all_entries()
        self.assertEqual(len(dEntries), 3)
        self.assertTrue(oPhysCardSet2.name in dEntries)
        self.assertTrue(oPhysCardSet1.name in dEntries)
        self.assertTrue(oMyCollection.name in dEntries)
        self.assertEqual(dEntries[oPhysCardSet1.name][2], oMyCollection.name)

        # Check it loads correctly
        # Destroy some existing data
        # pylint: disable=not-an-iterable
        # SQLObject confuses pylint
        aCardSet1 = sorted([x.abstractCard.name for x in oPhysCardSet1.cards])
        aCardSet2 = sorted([x.abstractCard.name for x in oPhysCardSet2.cards])
        # pylint: enable=not-an-iterable

        delete_physical_card_set(oMyCollection.name)
        delete_physical_card_set(oPhysCardSet1.name)

        self.assertEqual(PhysicalCardSet.select().count(), 1)

        oZipFile.do_restore_from_zip(oLogHandler=oHandler)
        self.assertEqual(oZipFile.get_warnings(), [])
        self.assertEqual(oHandler.fTot, 3)

        self.assertEqual(PhysicalCardSet.select().count(), 3)

        oMyCollection = IPhysicalCardSet('My Collection')
        oPhysCardSet1 = IPhysicalCardSet(CARD_SET_NAMES[0])
        oPhysCardSet2 = IPhysicalCardSet(CARD_SET_NAMES[1])
        self.assertEqual(oPhysCardSet1.comment, 'A test comment')
        self.assertEqual(oPhysCardSet2.author, 'A different author')
        self.assertNotEqual(oPhysCardSet1.parent, None)
        self.assertEqual(oPhysCardSet1.parent.id, oMyCollection.id)
        self.assertEqual(
            sorted([x.abstractCard.name for x in oPhysCardSet1.cards]),
            aCardSet1)
        self.assertEqual(oPhysCardSet2.parent, None)
        self.assertEqual(
            sorted([x.abstractCard.name for x in oPhysCardSet2.cards]),
            aCardSet2)

        self.assertEqual(
            sorted([x.abstractCard.name for x in oMyCollection.cards]),
            sorted([x.abstractCard.name for x in aPhysCards]))
        self.assertEqual(len(oPhysCardSet1.cards), 6)
        self.assertEqual(len(oPhysCardSet2.cards), 5)
예제 #17
0
    def test_basic(self):
        """Basic card set holder tests."""
        # pylint: disable=too-many-statements, too-many-locals
        # Want a long, sequential test case to minimise repeated setup
        # Everything is in the database, so should be no problems
        dSet1 = {
            '.44 Magnum': [3, None],
            'AK-47': [2, 'LotN'],
            'Abebe': [3, 'LoB'],
            'Abombwe': [3, 'LoB'],
            'Abbot': [1, 'Third Edition'],
        }
        oCSH = CardSetHolder()
        aExpectedPrintings = []

        for sCardName, aInfo in dSet1.items():
            iCnt, sExpName = aInfo
            oCSH.add(iCnt, sCardName, sExpName, None)
            if sExpName:
                oExp = IExpansion(sExpName)
                oThisPrint = IPrinting((oExp, None))
            else:
                oThisPrint = None
            aExpectedPrintings.extend([oThisPrint] * iCnt)

        aExpectedPrintings.sort(key=lambda x: x.id if x else -1)
        self.assertRaises(RuntimeError, oCSH.create_pcs)
        oCSH.name = 'Test Set 1'
        oCSH.create_pcs()
        oCS = IPhysicalCardSet('Test Set 1')
        self.assertEqual(len(oCS.cards), 12)
        oPCSFilter = BaseFilters.PhysicalCardSetFilter('Test Set 1')
        oAbbotFilter = BaseFilters.FilterAndBox(
            [oPCSFilter, BaseFilters.SpecificCardFilter('Abbot')])
        aCSCards = [
            IAbstractCard(x).name for x in oAbbotFilter.select(
                MapPhysicalCardToPhysicalCardSet).distinct()
        ]
        self.assertEqual(aCSCards, [u'Abbot'])
        oVampireFilter = BaseFilters.FilterAndBox(
            [oPCSFilter, BaseFilters.CardTypeFilter('Vampire')])
        aCSCards = [
            IAbstractCard(x).name for x in oVampireFilter.select(
                MapPhysicalCardToPhysicalCardSet).distinct()
        ]
        self.assertEqual(
            aCSCards,
            [u'Abebe (Group 4)', u'Abebe (Group 4)', u'Abebe (Group 4)'])
        aPrintings = [oCard.printing for oCard in oCS.cards]
        aPrintings.sort(key=lambda x: x.id if x else -1)
        self.assertEqual(aPrintings, aExpectedPrintings)

        oCSH.name = 'Test Set 2'
        oCSH.parent = 'Test Set 1'
        self.assertRaises(RuntimeError, oCSH.remove, 1, 'Abbot', None, None)
        self.assertRaises(RuntimeError, oCSH.remove, 2, 'Abbot',
                          'Third Edition', None)
        oCSH.remove(1, 'Abbot', 'Third Edition', None)
        oCSH.remove(1, 'Abombwe', 'LoB', None)
        oCSH.create_pcs()

        oCS2 = IPhysicalCardSet('Test Set 2')
        self.assertEqual(oCS2.parent, oCS)
        self.assertEqual(len(oCS2.cards), 10)

        oPCSFilter = BaseFilters.PhysicalCardSetFilter('Test Set 2')
        oAbbotFilter = BaseFilters.FilterAndBox(
            [oPCSFilter, BaseFilters.SpecificCardFilter('Abbot')])
        aCSCards = [
            IAbstractCard(x).name for x in oAbbotFilter.select(
                MapPhysicalCardToPhysicalCardSet).distinct()
        ]
        self.assertEqual(aCSCards, [])
        oVampireFilter = BaseFilters.FilterAndBox(
            [oPCSFilter, BaseFilters.CardTypeFilter('Vampire')])
        aCSCards = [
            IAbstractCard(x).name for x in oVampireFilter.select(
                MapPhysicalCardToPhysicalCardSet).distinct()
        ]
        self.assertEqual(
            aCSCards,
            [u'Abebe (Group 4)', u'Abebe (Group 4)', u'Abebe (Group 4)'])

        # Misspelt cards - the default lookup should exclude these
        dSet2 = {
            '.44 Magnum': [3, None],
            'Abede': [3, 'LoB'],
        }
        oCSH = CardSetHolder()
        for sCardName, aInfo in dSet2.items():
            iCnt, sExpName = aInfo
            oCSH.add(iCnt, sCardName, sExpName, None)

        oCSH.name = 'Test Set 3'

        oCSH.create_pcs()

        oCS = IPhysicalCardSet('Test Set 3')
        self.assertEqual(len(oCS.cards), 3)
        oPCSFilter = BaseFilters.PhysicalCardSetFilter('Test Set 3')
        oGunFilter = BaseFilters.FilterAndBox(
            [oPCSFilter,
             BaseFilters.SpecificCardFilter('.44 Magnum')])
        aCSCards = [
            IAbstractCard(x).name for x in oGunFilter.select(
                MapPhysicalCardToPhysicalCardSet).distinct()
        ]
        self.assertEqual(aCSCards,
                         [u'.44 Magnum', u'.44 Magnum', '.44 Magnum'])
        oVampireFilter = BaseFilters.FilterAndBox(
            [oPCSFilter, BaseFilters.CardTypeFilter('Vampire')])
        aCSCards = [
            IAbstractCard(x).name for x in oVampireFilter.select(
                MapPhysicalCardToPhysicalCardSet).distinct()
        ]
        self.assertEqual(aCSCards, [])

        # Misspelt expansions - all cards should be added, but some with
        # None for the expansion
        dSet3 = {
            'AK-47': [2, 'Lords of the Knight'],
            'Abebe': [3, 'Legacy of Bllod'],
        }

        oCSH = CardSetHolder()
        for sCardName, aInfo in dSet3.items():
            iCnt, sExpName = aInfo
            oCSH.add(iCnt, sCardName, sExpName, None)

        aExpectedPrintings = [None] * 5

        # Also check parent warnings
        oCSH.parent = 'Test Set 5'
        oCSH.name = 'Test Set 4'
        self.assertEqual(oCSH.get_parent_pcs(), None)
        self.assertNotEqual(len(oCSH.get_warnings()), 0)
        oCSH.clear_warnings()
        self.assertEqual(len(oCSH.get_warnings()), 0)
        oCSH.create_pcs()
        self.assertNotEqual(len(oCSH.get_warnings()), 0)

        oCS = IPhysicalCardSet('Test Set 4')
        self.assertEqual(len(oCS.cards), 5)
        oPCSFilter = BaseFilters.PhysicalCardSetFilter('Test Set 4')
        oGunFilter = BaseFilters.FilterAndBox(
            [oPCSFilter, BaseFilters.SpecificCardFilter('AK-47')])
        aCSCards = [
            IAbstractCard(x).name for x in oGunFilter.select(
                MapPhysicalCardToPhysicalCardSet).distinct()
        ]
        self.assertEqual(aCSCards, [u'AK-47', u'AK-47'])
        oVampireFilter = BaseFilters.FilterAndBox(
            [oPCSFilter, BaseFilters.CardTypeFilter('Vampire')])
        aCSCards = [
            IAbstractCard(x).name for x in oVampireFilter.select(
                MapPhysicalCardToPhysicalCardSet).distinct()
        ]
        self.assertEqual(
            aCSCards,
            [u'Abebe (Group 4)', u'Abebe (Group 4)', u'Abebe (Group 4)'])

        aPrintings = [oCard.printing for oCard in oCS.cards]
        aPrintings.sort(key=lambda x: x.id if x else -1)
        self.assertEqual(aPrintings, aExpectedPrintings)
    def test_physical_card_set(self):
        """Test physical card set object"""
        # pylint: disable=too-many-statements, too-many-locals
        # Want a long, sequential test case to minimise
        # repeated setups, so it has lots of lines + variables
        aAddedPhysCards = get_phys_cards()
        # We have a physical card list, so create some physical card sets

        oPhysCardSet1 = PhysicalCardSet(name=CARD_SET_NAMES[2])

        # Add cards to the physical card sets

        for iLoop in range(5):
            # pylint: disable=no-member
            # SQLObect confused pylint
            oPhysCardSet1.addPhysicalCard(aAddedPhysCards[iLoop].id)
        oPhysCardSet1.syncUpdate()

        self.assertEqual(len(oPhysCardSet1.cards), 5)
        # Because we repeat .44 Magnum 3 times
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[0].id).count(), 3)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[4].id).count(), 1)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[7].id).count(), 0)

        oPhysCardSet2 = PhysicalCardSet(name=CARD_SET_NAMES[1],
                                        comment='Test 2',
                                        author=oPhysCardSet1.author)

        self.assertEqual(oPhysCardSet2.name, CARD_SET_NAMES[1])
        self.assertEqual(oPhysCardSet2.author, oPhysCardSet1.author)
        self.assertEqual(oPhysCardSet2.comment, 'Test 2')

        for iLoop in range(3, 8):
            # pylint: disable=no-member
            # SQLObect confused pylint
            oPhysCardSet2.addPhysicalCard(aAddedPhysCards[iLoop].id)
        oPhysCardSet2.syncUpdate()

        self.assertEqual(len(oPhysCardSet2.cards), 5)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[0].id).count(), 3)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[4].id).count(), 2)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[7].id).count(), 1)

        oPhysCardSet3 = make_set_1()
        self.assertEqual(len(oPhysCardSet3.cards), len(aAddedPhysCards))

        self.assertEqual(oPhysCardSet3.name, CARD_SET_NAMES[0])
        self.assertEqual(oPhysCardSet3.comment, 'A test comment')

        oPhysCardSet4 = IPhysicalCardSet(CARD_SET_NAMES[0])

        self.assertEqual(oPhysCardSet3, oPhysCardSet4)

        # pylint: disable=no-member
        # SQLObject confuses pylint
        oPhysCardSet5 = PhysicalCardSet.byName(CARD_SET_NAMES[1])
        self.assertEqual(oPhysCardSet2, oPhysCardSet5)

        # Check Deletion

        # pylint: disable=not-an-iterable
        # SQLOBject confuses pylint
        for oCard in oPhysCardSet3.cards:
            oPhysCardSet3.removePhysicalCard(oCard.id)
        # pylint: enable=not-an-iterable

        self.assertEqual(len(oPhysCardSet3.cards), 0)
        PhysicalCardSet.delete(oPhysCardSet3.id)

        self.assertRaises(SQLObjectNotFound, PhysicalCardSet.byName,
                          CARD_SET_NAMES[0])

        delete_physical_card_set(CARD_SET_NAMES[1])

        self.assertRaises(SQLObjectNotFound, PhysicalCardSet.byName,
                          CARD_SET_NAMES[1])
        # pylint: enable=no-member

        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[0].id).count(), 3)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[4].id).count(), 1)

        delete_physical_card_set(CARD_SET_NAMES[2])

        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[0].id).count(), 0)
        self.assertEqual(
            MapPhysicalCardToPhysicalCardSet.selectBy(
                physicalCardID=aAddedPhysCards[4].id).count(), 0)