Exemplo n.º 1
0
 def test_basic(self):
     """Set of simple tests of the SutekhMainWindow"""
     # Add card sets needed for the tests
     oPhysCardSet1 = PhysicalCardSet(name='My Collection')
     PhysicalCardSet(name='Test Set 1', parent=oPhysCardSet1)
     PhysicalCardSet(name='Test Set 2', parent=oPhysCardSet1)
     self.oWin.setup(self.oConfig)
     # Check we have the correct panes in place
     self.assertTrue(self.oWin.is_open_by_menu_name('Full Card List'))
     self.assertTrue(self.oWin.is_open_by_menu_name('Card Set List'))
     self.assertTrue(self.oWin.is_open_by_menu_name('Card Text'))
     self.assertNotEqual(
         self.oWin.find_cs_pane_by_set_name('My Collection'), [])
     # Remove a pane
     for oPane in self.oWin.aOpenFrames[:]:
         if oPane.title == 'Card Text':
             self.oWin.remove_frame(oPane)
         if oPane.title == 'Card Set List':
             oSetList = oPane
     self.assertFalse(self.oWin.is_open_by_menu_name('Card Text'))
     # Check focus
     self.assertEqual(self.oWin.focussed_pane, None)
     self.oWin.win_focus(None, None, oSetList)
     self.assertEqual(self.oWin.focussed_pane, oSetList)
     # Replace frame
     self.oWin.replace_with_card_text(None)
     self.assertTrue(self.oWin.is_open_by_menu_name('Card Text'))
     # Adding the pane will unset the focus
     self.assertEqual(self.oWin.focussed_pane, None)
     self.assertFalse(self.oWin.is_open_by_menu_name('Card Set List'))
     # Add a pane again
     self.oWin.add_new_pcs_list(None)
     self.assertEqual(self.oWin.focussed_pane, None)
     self.assertTrue(self.oWin.is_open_by_menu_name('Card Set List'))
     # Check that we can add multiple copies of My Collection
     self.oWin.add_new_physical_card_set('My Collection')
     self.assertEqual(
         len(self.oWin.find_cs_pane_by_set_name('My Collection')), 2)
     self.oWin.add_new_physical_card_set('My Collection')
     self.assertEqual(
         len(self.oWin.find_cs_pane_by_set_name('My Collection')), 3)
     oPane = self.oWin.find_cs_pane_by_set_name('My Collection')[0]
     self.oWin.remove_frame(oPane)
     self.assertEqual(
         len(self.oWin.find_cs_pane_by_set_name('My Collection')), 2)
     oPane = self.oWin.find_cs_pane_by_set_name('My Collection')[0]
     self.oWin.minimize_to_toolbar(oPane)
     self.assertEqual(len(self.oWin.aClosedFrames), 1)
     self.assertEqual(len(self.oWin.aOpenFrames), 4)
     self.assertTrue(oPane in self.oWin.aClosedFrames)
     self.assertFalse(oPane in self.oWin.aOpenFrames)
     self.oWin.save_frames()
     self.oWin.remove_frame(oPane)
     self.assertEqual(len(self.oWin.aClosedFrames), 0)
     self.oWin.restore_from_config()
     self.assertEqual(len(self.oWin.aClosedFrames), 1)
     self.assertEqual(len(self.oWin.aOpenFrames), 4)
     self.assertEqual(
         len(self.oWin.find_cs_pane_by_set_name('My Collection')), 2)
Exemplo n.º 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)
Exemplo n.º 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)
Exemplo n.º 4
0
    def test_basic(self):
        """Set of simple tests of the CardTextFrame"""
        # 'My Collection' is needed for default config
        _oMyCollection = PhysicalCardSet(name='My Collection')
        self.oWin.setup(self.oConfig)
        # Get the card text frame
        oCardTextFrame = self.oWin._oCardTextPane
        # Card text should start empty
        self.assertEqual(oCardTextFrame.view._oBuf.get_all_text(), "")
        # Set a card
        oCard = make_card('Aire of Elation', None)
        oCardTextFrame.set_card_text('set_card_text', oCard)
        self.assertEqual(oCardTextFrame.view._oBuf.get_all_text(), AIRE)
        # Check expansion works as expected
        oCard = make_card('Aire of Elation', 'Anarchs')
        oCardTextFrame.set_card_text('set_card_text', oCard)
        self.assertEqual(oCardTextFrame.view._oBuf.get_all_text(), AIRE)
        # Check different cards
        oCard = make_card('Alexandra', None)
        oCardTextFrame.set_card_text('set_card_text', oCard)
        self.assertEqual(oCardTextFrame.view._oBuf.get_all_text(), ALEXANDRA)

        oCard = make_card('Gypsies', None)
        oCardTextFrame.set_card_text('set_card_text', oCard)
        self.assertEqual(oCardTextFrame.view._oBuf.get_all_text(), GYPSIES)

        oCard = make_card('High Top', None)
        oCardTextFrame.set_card_text('set_card_text', oCard)
        self.assertEqual(oCardTextFrame.view._oBuf.get_all_text(), HIGH_TOP)
Exemplo n.º 5
0
 def _get_twda_holders(self):
     """Return all the TWDA holders in the current database"""
     aHolders = []
     for oCS in PhysicalCardSet.select():
         oMatch = self.oTWDARegex.match(oCS.name)
         if oMatch:
             aHolders.append(oCS)
     return aHolders
    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]))
Exemplo n.º 7
0
 def check_enabled(self):
     """check for starter decks in the database and disable menu if not"""
     bEnabled = False
     for oCS in PhysicalCardSet.select():
         oMatch = self.oStarterRegex.match(oCS.name)
         if oMatch:
             bEnabled = True
             break
     return bEnabled
Exemplo n.º 8
0
 def _cache_starters(self):
     """Lookup the starter decks and cache them to avoid repeated queries"""
     for oCS in PhysicalCardSet.select():
         for _sType, oRegex in (('Starters', self.oStarterRegex),
                                ('Fixed', self.oFixedRegex),
                                ('Demos', self.oDemoRegex)):
             oMatch = oRegex.match(oCS.name)
             if oMatch:
                 self._aStarters.append(oCS)
Exemplo n.º 9
0
 def _get_twda_names(self):
     """Get names of all the TWDA entries in the current database"""
     aNames = []
     for oCS in PhysicalCardSet.select():
         if not oCS.parent or not oCS.inuse:
             continue
         oMatch = self.oTWDARegex.match(oCS.parent.name)
         if oMatch:
             aNames.append(oCS.name)
     return aNames
Exemplo n.º 10
0
    def _get_decks(self, aUrls, aDates, aHashes):
        """Unzip a file containing the decks."""
        aZipHolders = []
        aToUnzip, aToReplace = self._get_decks_to_download(aUrls, aDates,
                                                           aHashes)
        if not aToUnzip:
            return False
        # We download everything first, so we don't delete card sets which
        # fail to download.
        oBinLogHandler = BinnedCountLogHandler()
        oProgressDialog = ProgressDialog()
        oProgressDialog.set_description("Downloading TWDA data")
        oLogger = Logger('Download zip files')
        oLogger.addHandler(oBinLogHandler)
        oBinLogHandler.set_dialog(oProgressDialog)
        oBinLogHandler.set_tot_bins(len(aToUnzip))
        oProgressDialog.show()
        # We sort the list of urls to download for cosmetic reasons
        for sUrl, sTWDA, sHash in sorted(aToUnzip, key=lambda x: x[1]):
            oFile = urlopen_with_timeout(sUrl,
                                         fErrorHandler=gui_error_handler,
                                         bBinary=True)
            oProgressDialog.set_description('Downloading %s' % sTWDA)
            try:

                sData = fetch_data(oFile, sHash=sHash,
                                   oLogHandler=oBinLogHandler,
                                   fErrorHandler=gui_error_handler)
            except HashError:
                do_complaint_error("Checksum failed for %s\nSkipping"
                                   % sTWDA)
                # Don't delete this, since we're not replacing it
                aToReplace.remove(sTWDA)
                continue
            oZipFile = ZipFileWrapper(BytesIO(sData))
            aZipHolders.append(oZipFile)
            oBinLogHandler.inc_cur_bin()
        oProgressDialog.destroy()

        # Bomb out if we're going to end up doing nothing
        if not aZipHolders:
            return False

        # Delete all TWDA entries in the holders we replace
        # We do this to handle card sets being removed from the TWDA
        # correctly
        aToDelete = []
        for oCS in list(PhysicalCardSet.select()):
            if not oCS.parent:
                continue
            if oCS.parent.name in aToReplace:
                aToDelete.append(oCS.name)

        return unzip_files_into_db(aZipHolders, "Adding TWDA Data",
                                   self.parent, aToDelete)
Exemplo n.º 11
0
def write_all_pcs(sDir=''):
    """Write all the Physical Card Sets into files in the given directory"""
    oPhysicalCardSets = PhysicalCardSet.select()
    aList = []
    for oPCS in oPhysicalCardSets:
        sFName = safe_filename(oPCS.name)
        sFileName = gen_temp_file('pcs_' + sFName + '_', sDir)
        oWriter = PhysicalCardSetXmlFile(sFileName)
        aList.append(oWriter)
        oWriter.write(oPCS.name)
    return aList
    def test_clean_empty(self):
        """Test clean_empty works as desired."""
        oRoot = PhysicalCardSet(name='Root')
        oChild = PhysicalCardSet(name='Child', parent=oRoot)
        aChildren = []
        for iCnt in range(4):
            oSet = PhysicalCardSet(name='Card Set %d' % iCnt, parent=oChild)
            aChildren.append(oSet)

        aSets = get_current_card_sets()
        self.assertEqual(len(aSets), 6)
        # Check that clean_emtpy doesn't remove any sets we say were existing
        clean_empty(aSets, aSets)
        self.assertEqual(len(get_current_card_sets()), 6)
        # Check that clean_empty removes all the children if we say none
        # were existing
        clean_empty([x.name for x in aChildren], [])
        aSets = get_current_card_sets()
        self.assertEqual(len(aSets), 2)
        self.assertTrue(oChild.name in aSets)
        self.assertTrue(oRoot.name in aSets)
Exemplo n.º 13
0
 def old_database_count(self, oConn):
     """Check number of items in old DB fro progress bars, etc."""
     oVer = DatabaseVersion()
     iCount = 14  # Card property tables
     if oVer.check_tables_and_versions([AbstractCard],
                                       [AbstractCard.tableversion], oConn):
         iCount += AbstractCard.select(connection=oConn).count()
     elif oVer.check_tables_and_versions([AbstractCard], [5], oConn):
         iCount += AbstractCard_v5.select(connection=oConn).count()
     if oVer.check_tables_and_versions([PhysicalCard],
                                       [PhysicalCard.tableversion], oConn):
         iCount += PhysicalCard.select(connection=oConn).count()
     elif oVer.check_tables_and_versions([PhysicalCard], [2], oConn):
         iCount += PhysicalCard_v2.select(connection=oConn).count()
     if oVer.check_tables_and_versions([PhysicalCardSet],
                                       [PhysicalCardSet.tableversion],
                                       oConn):
         iCount += PhysicalCardSet.select(connection=oConn).count()
     elif oVer.check_tables_and_versions([PhysicalCardSet], [6], oConn):
         iCount += PhysicalCardSet.select(connection=oConn).count()
     return iCount
def make_set_1():
    """Make the first card set.

       Function as this is also used in the io tests.
       """

    aAddedPhysCards = get_phys_cards()
    oPhysCardSet1 = PhysicalCardSet(name=CARD_SET_NAMES[0])
    oPhysCardSet1.comment = 'A test comment'
    oPhysCardSet1.author = 'A test author'
    for oCard in aAddedPhysCards:
        # pylint: disable=no-member
        # SQLObect confused pylint
        oPhysCardSet1.addPhysicalCard(oCard.id)
    oPhysCardSet1.syncUpdate()
    return oPhysCardSet1
Exemplo n.º 15
0
    def test_basic(self):
        """Set of simple tests of the LogViewFrame"""
        # Add the log view frame
        oOutput = BytesIO()
        # 'My Collection' is needed for default config
        _oMyCollection = PhysicalCardSet(name='My Collection')
        self.oWin.setup(self.oConfig)
        oNewFrame = self.oWin.add_new_log_view_frame(None)
        # Clear the log history of any existing entries
        self.oWin.gui_log_handler.aQueue.clear()
        oNewFrame.reload()
        # Check that the frame is properly cleared
        oNewFrame.view.export_buffer(oOutput)
        self.assertEqual(oOutput.getvalue(), b'')
        # log several messages
        logging.info(self.INFO_MSG)
        logging.debug(self.DEBUG_MSG)
        logging.error(self.ERROR_MSG)
        logging.warning(self.WARN_MSG)
        # Assert that they're all present
        oNewFrame.reload()
        oNewFrame.view.export_buffer(oOutput)
        sResult = oOutput.getvalue()
        self.assertTrue(b'ERROR' in sResult)
        self.assertTrue(b'WARN' in sResult)
        self.assertTrue(b'INFO' in sResult)
        self.assertTrue(b'DEBUG' in sResult)

        self.assertTrue(self.ERROR_MSG in sResult)
        self.assertTrue(self.WARN_MSG in sResult)
        self.assertTrue(self.INFO_MSG in sResult)
        self.assertTrue(self.DEBUG_MSG in sResult)
        # Test filtering
        oOutput.truncate(0)
        oOutput.seek(0)

        oNewFrame.set_filter_level(logging.WARN)
        oNewFrame.view.export_buffer(oOutput)
        sResult = oOutput.getvalue()
        self.assertTrue(b'ERROR' in sResult)
        self.assertTrue(b'WARN' in sResult)
        self.assertTrue(self.ERROR_MSG in sResult)
        self.assertTrue(self.WARN_MSG in sResult)

        self.assertTrue(b'INFO' not in sResult)
        self.assertTrue(b'DEBUG' not in sResult)
        self.assertTrue(self.INFO_MSG not in sResult)
        self.assertTrue(self.DEBUG_MSG not in sResult)
Exemplo n.º 16
0
    def test_show_errata(self):
        """Test with 'show errata markers' set"""
        # 'My Collection' is needed for default config
        _oMyCollection = PhysicalCardSet(name='My Collection')
        self.oWin.setup(self.oConfig)
        # Get the card text frame
        oCardTextFrame = self.oWin._oCardTextPane
        # Card text should start empty
        self.assertEqual(oCardTextFrame.view._oBuf.get_all_text(), "")
        # Set the 'show errata markers' option
        self.oConfig.set_show_errata_markers(True)

        oCard = make_card('Gypsies', None)
        oCardTextFrame.set_card_text('set_card_text', oCard)
        self.assertEqual(oCardTextFrame.view._oBuf.get_all_text(),
                         GYPSIES_ERRATA)
Exemplo n.º 17
0
    def test_print_card_sets(self):
        """Test printing a card set hierachy"""
        # Create a 3 level hierachy
        oRoot = PhysicalCardSet(name='Root')
        oChild1 = PhysicalCardSet(name='Child 1', parent=oRoot)
        oChild2 = PhysicalCardSet(name='Child 2', parent=oRoot)
        PhysicalCardSet(name='Child 3', parent=oRoot)
        PhysicalCardSet(name='GC 1', parent=oChild1)
        PhysicalCardSet(name='GC 2', parent=oChild1)
        PhysicalCardSet(name='GC 3', parent=oChild1)
        PhysicalCardSet(name='GC 4', parent=oChild2)

        with patch('sys.stdout', new_callable=StringIO) as oMock:
            print_card_list('Root')
            self.assertEqual(oMock.getvalue(), TREE_1)

        with patch('sys.stdout', new_callable=StringIO) as oMock:
            print_card_list('Child 1')
            self.assertEqual(oMock.getvalue(), TREE_2)
Exemplo n.º 18
0
    def _make_pcs_from_cluster(self, iClusterId):
        """Create a Card Set from the chosen cluster"""
        sDeckName = '_cluster_deck_%d' % (iClusterId, )

        # Check Deck Doesn't Exist
        if check_cs_exists(sDeckName):
            do_complaint_error("Card Set %s already exists." % sDeckName)
            return

        # Create Deck
        oDeck = PhysicalCardSet(name=sDeckName)

        # pylint: disable=no-member
        # SQLObject confuses pylint
        aCards = [
            IPhysicalCard(self._aCards[x]) for x in self._aClusters[iClusterId]
        ]
        self._commit_cards(oDeck, aCards)
        self._open_cs(sDeckName, True)
Exemplo n.º 19
0
 def test_delete_with_physical_filters(self):
     """Test deleting cards with physical filters in play."""
     oColl = PhysicalCardSet(name='My Collection')
     # Add some cards
     aCards = [("Ghoul Retainer", "Jyhad", None)] * 2 + \
         [("Ghoul Retainer", "Jyhad", "Variant Printing")] * 3 + \
         [("Off Kilter", "HttB", None)] * 3 + \
         [("Off Kilter", "HttB", "No Draft Text")] * 4
     aPhysCards = []
     for (sName, sExp, sPrint) in aCards:
         oCard = make_card(sName, sExp, sPrint)
         aPhysCards.append(oCard)
     for oCard in aPhysCards:
         # pylint: disable=no-member
         # SQLObject confuses pylint
         oColl.addPhysicalCard(oCard.id)
         oColl.syncUpdate()
     self.assertEqual(len(oColl.cards), 12)
     self.oWin.setup(self.oConfig)
     # Remove the unneeded panes
     for oPane in self.oWin.aOpenFrames[:]:
         if oPane.title in ('Card Text', 'Card Set List', 'Full Card List'):
             self.oWin.remove_frame(oPane)
         if oPane.title == 'My Collection':
             oMyColl = oPane
     oMyColl.view.toggle_editable(True)
     # Test deleting with no filter works as expected
     self._select_cards(oMyColl, [(u'Ghoul Retainer', ), (u'Off Kilter', )])
     oEvent = Gdk.Event()
     oEvent.type = Gdk.EventType.KEY_PRESS
     oEvent.key.keyval = int(Gdk.keyval_from_name('minus'))
     # Check that we can delete all the way
     # We should remove 2 cards each time until we've removed
     # 5 Ghoul Retainers
     for iExpected in range(10, 0, -2):
         oMyColl.view.key_press(oMyColl, oEvent.key)
         self.assertEqual(len(oColl.cards), iExpected)
     # Then remove 1 card for the last 2
     for iExpected in range(1, -1, -1):
         oMyColl.view.key_press(oMyColl, oEvent.key)
         self.assertEqual(len(oColl.cards), iExpected)
     oColl.syncUpdate()
     for oCard in aPhysCards:
         # pylint: disable=no-member
         # SQLObject confuses pylint
         oColl.addPhysicalCard(oCard.id)
         oColl.syncUpdate()
     self.assertEqual(len(oColl.cards), 12)
     oMyColl.reload()
     # Test deleting with physical printing filter works as expected
     oFilter = BaseFilters.PhysicalPrintingFilter(
         'Jyhad (Variant Printing)')
     oMyColl.view.set_filter(oFilter)
     oMyColl.reload()
     self._select_cards(oMyColl, [(u'Ghoul Retainer', )])
     # Each removal should remove 1 card
     for iExpected in range(11, 8, -1):
         oMyColl.view.key_press(oMyColl, oEvent.key)
         self.assertEqual(len(oColl.cards), iExpected)
     # Further removals have no effect
     oMyColl.view.key_press(oMyColl, oEvent.key)
     self.assertEqual(len(oColl.cards), 9)
     oMyColl.view.key_press(oMyColl, oEvent.key)
     self.assertEqual(len(oColl.cards), 9)
     # Test deleting with physical expansion filter works as expected
     oFilter = BaseFilters.PhysicalExpansionFilter('Heirs to the Blood')
     oMyColl.view.set_filter(oFilter)
     oMyColl.reload()
     self._select_cards(oMyColl, [(u'Off Kilter', )])
     for iExpected in range(8, 1, -1):
         oMyColl.view.key_press(oMyColl, oEvent.key)
         self.assertEqual(len(oColl.cards), iExpected)
     # Asset that all the remaining 2 cards are both Jyhad (No variant)
     # Ghoul retainers
     # pylint: disable=not-an-iterable
     # SQLObject confuses pylint here
     for oCard in oColl.cards:
         self.assertEqual(oCard.abstractCard.name, "Ghoul Retainer")
         self.assertEqual(IPrintingName(oCard), "Jyhad")
Exemplo n.º 20
0
    def test_basic(self):
        """Set of simple tests of the CardSetFrame"""
        # 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

        # Add card sets needed for the tests
        # pylint: disable=unsupported-membership-test, not-an-iterable
        # Checks on RelatedJoins confuse pylint
        oPhysCardSet = PhysicalCardSet(name='My Collection')
        oPCS2 = PhysicalCardSet(name='Test Set 1', parent=oPhysCardSet)
        # Add some cards
        aCards = [('AK-47', None), ('Bronwen', 'SW'), ('Cesewayo', None),
                  ('Anna "Dictatrix11" Suljic', 'NoR'),
                  ('Ablative Skin', 'Sabbat')] + [('Alexandra', 'CE'),
                                                  ('Alexandra', None),
                                                  ('Ablative Skin', None)] * 5
        aPhysCards = []
        for sName, sExp in aCards:
            oCard = make_card(sName, sExp)
            aPhysCards.append(oCard)
        for oCard in aPhysCards:
            # pylint: disable=no-member
            # SQLObject confuses pylint
            oPhysCardSet.addPhysicalCard(oCard.id)
            oPhysCardSet.syncUpdate()
        self.oWin.setup(self.oConfig)
        # Remove the unneeded panes
        for oPane in self.oWin.aOpenFrames[:]:
            if oPane.title in ('Card Text', 'Card Set List'):
                self.oWin.remove_frame(oPane)
            if oPane.title == 'Full Card List':
                oWWList = oPane
            if oPane.title == 'My Collection':
                oMyColl = oPane
        # Add a set, not opened editable
        oNewFrame = self.oWin.add_new_physical_card_set('Test Set 1', False)
        # Add one of the new card sets, as an empty, editable set
        # Create selection of cards from the WW card list and
        # paste it into the new card set
        oFrame = oWWList
        self._select_cards(oFrame, [(u'AK-47', None),
                                    (u'AK-47', u'Lords of the Night')])
        self.assertEqual(oFrame.view.get_selection().count_selected_rows(), 2)
        # Copy
        oFrame.view.copy_selection()
        oNewFrame.view.do_paste()
        self.assertEqual(len(oPCS2.cards), 0)
        self.oWin.remove_frame(oNewFrame)
        # Reopen the card set, only editable this time
        oNewFrame = self.oWin.add_new_physical_card_set('Test Set 1', True)
        oNewFrame.view.do_paste()
        self.assertEqual(len(oPCS2.cards), 2)
        # Check we've pasted the right cards
        self.assertTrue(make_card(u'AK-47', None) in oPCS2.cards)
        self.assertTrue(
            make_card(u'AK-47', u'Lords of the Night') in oPCS2.cards)
        # Select cards in new card set and change numbers
        self._select_cards(oNewFrame, [(u'AK-47', None),
                                       (u'AK-47', u'Lords of the Night')])
        # Generate key_press event
        oEvent = Gdk.Event()
        oEvent.type = Gdk.EventType.KEY_PRESS
        oEvent.key.keyval = int(Gdk.keyval_from_name('4'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 8)
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 8)
        oEvent.key.keyval = int(Gdk.keyval_from_name('1'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 2)
        oEvent.key.keyval = int(Gdk.keyval_from_name('plus'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 4)
        oEvent.key.keyval = int(Gdk.keyval_from_name('minus'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 2)
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 0)
        # Select all and delete it from the new card set
        oNewFrame.view.do_paste()
        self.assertEqual(len(oPCS2.cards), 2)
        self._select_cards(oNewFrame, [(u'AK-47', u'Lords of the Night')])
        oNewFrame.view.del_selection()
        self.assertEqual(len(oPCS2.cards), 1)
        self._select_cards(oNewFrame, [(u'AK-47', None)])
        oEvent.key.keyval = int(Gdk.keyval_from_name('plus'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 2)
        oNewFrame.view.del_selection()
        self.assertEqual(len(oPCS2.cards), 0)
        oNewFrame.view.do_paste()
        self.assertEqual(len(oPCS2.cards), 2)
        # Select card from My Collection and paste it into the card set
        oFrame = oMyColl
        # set editable off
        oNewFrame.view.toggle_editable(False)
        # Verify that trying to paste the selection does nothing
        self._select_cards(oFrame,
                           [(u'AK-47', None), ('Ablative Skin', 'Sabbat'),
                            ('Alexandra (Group 2)', 'Camarilla Edition')])
        oFrame.view.copy_selection()
        oNewFrame.view.do_paste()
        self.assertEqual(len(oPCS2.cards), 2)
        # set editable on and verify that we can change the numbers
        oNewFrame.view.toggle_editable(True)
        oNewFrame.view.do_paste()
        # We should get 5 copies of Alexandra from My Collection
        self.assertEqual(len(oPCS2.cards), 9)
        self.assertEqual(
            len([
                x for x in oPCS2.cards
                if IAbstractCard(x).name == 'Alexandra (Group 2)'
            ]), 5)
        # Tests involving the top level selection
        oFrame = oWWList
        self._select_cards(oFrame, [(u'AK-47', ), (u'Ablative Skin', )])
        oFrame.view.copy_selection()
        oNewFrame.view.do_paste()
        self.assertEqual(len(oPCS2.cards), 11)
        self.assertEqual(
            len([
                x for x in oPCS2.cards
                if IAbstractCard(x).name == 'Alexandra (Group 2)'
            ]), 5)
        self.assertEqual(
            len([x for x in oPCS2.cards if IAbstractCard(x).name == 'AK-47']),
            4)
        aCardNames = [oCard.abstractCard.name for oCard in oPCS2.cards]
        self._select_cards(oNewFrame, [(sName, ) for sName in aCardNames])
        oNewFrame.view.del_selection()
        self.assertEqual(len(oPCS2.cards), 0)
        oFrame = oMyColl
        self._select_cards(oFrame, [(u'AK-47', ), (u'Ablative Skin', )])
        oFrame.view.copy_selection()
        oNewFrame.view.do_paste()
        self.assertEqual(len(oPCS2.cards), 7)
        self.assertEqual(
            len([x for x in oPCS2.cards if IAbstractCard(x).name == 'AK-47']),
            1)
        self.assertEqual(
            len([
                x for x in oPCS2.cards
                if IAbstractCard(x).name == 'Ablative Skin'
            ]), 6)
        self.assertEqual(
            len([
                x for x in oPCS2.cards
                if IAbstractCard(x).name == 'Ablative Skin'
                and IPhysicalCard(x).printingID is None
            ]), 5)
        # Test involving top level and sublevel selections
        # Top level should override the sub selections, as being
        # most consitent behaviour
        self._select_cards(oNewFrame, [(u'AK-47', ), (u'AK-47', None),
                                       (u'AK-47', 'Lords of the Night')])
        oEvent = Gdk.Event()
        oEvent.type = Gdk.EventType.KEY_PRESS
        oEvent.key.keyval = int(Gdk.keyval_from_name('4'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 10)
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 10)
        oEvent.key.keyval = int(Gdk.keyval_from_name('1'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 7)
        oEvent.key.keyval = int(Gdk.keyval_from_name('plus'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 8)
        oEvent.key.keyval = int(Gdk.keyval_from_name('minus'))
        oNewFrame.view.key_press(oNewFrame, oEvent.key)
        self.assertEqual(len(oPCS2.cards), 7)
        # We should copy all the ones from My Collection
        # rename card set, and verify that everything gets updated properly

        # Check reload keep expanded works
        aExp1 = self.get_expanded(oFrame.view)
        oFrame.reload()
        aExp2 = self.get_expanded(oFrame.view)
        self.assertEqual(aExp1, aExp2)
        # Change some paths
        oFrame.view.collapse_all()
        for oPath in aExp1[::4]:
            oFrame.view.expand_to_path(oPath)
        aExp1 = self.get_expanded(oFrame.view)
        self.assertNotEqual(aExp1, aExp2)  # We have changed the paths
        oFrame.reload()
        aExp2 = self.get_expanded(oFrame.view)
        self.assertEqual(aExp1, aExp2)  # But reload has retained the new state
def make_set_3():
    """Copy of the second card set with Abebe dropped"""
    aAddedPhysCards = get_phys_cards()
    oPhysCardSet3 = PhysicalCardSet(name=CARD_SET_NAMES[2])

    oPhysCardSet3.comment = ('A formatted test comment\nA second line\n'
                             'A third line')
    oPhysCardSet3.author = 'A test author'
    oPhysCardSet3.annotations = 'Some Annotations'
    for iLoop in range(5, 10):
        # pylint: disable=no-member
        # SQLObect confused pylint
        oPC = aAddedPhysCards[iLoop]
        if IAbstractCard(oPC).name == 'Abebe (Group 4)':
            continue
        oPhysCardSet3.addPhysicalCard(oPC.id)
    for sName, sExpansion, iCount in SET_2_ONLY_CARDS:
        # pylint: disable=no-member
        # SQLObect confused pylint
        oPC = make_card(sName, sExpansion)
        for _iNum in range(iCount):
            oPhysCardSet3.addPhysicalCard(oPC.id)
    for sName, sExpansion, iCount in SET_3_ONLY_CARDS:
        # pylint: disable=no-member
        # SQLObect confused pylint
        oPC = make_card(sName, sExpansion)
        for _iNum in range(iCount):
            oPhysCardSet3.addPhysicalCard(oPC.id)
    oPhysCardSet3.syncUpdate()
    return oPhysCardSet3
    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)
Exemplo n.º 23
0
    def test_basic(self):
        """Test the basic functionality"""
        # Create card sets
        oRoot = PhysicalCardSet(name='Root')
        PhysicalCardSet(name='Sib')
        oChild = PhysicalCardSet(name='Child', parent=oRoot)
        oChild2 = PhysicalCardSet(name='Child 2 Branch', parent=oRoot)
        for iCnt in range(4):
            PhysicalCardSet(name='Card Set %d' % iCnt, parent=oChild)
        for iCnt in range(2):
            PhysicalCardSet(name='Child 2 Card Set %d' % iCnt, parent=oChild2)
        oWin = DummyWindow()
        oModel = CardSetManagementModel(oWin)
        oModel.enable_sorting()
        oModel.load()

        self.assertEqual(oModel.get_card_set_iterator(None).count(), 10)
        # expected failure
        self.assertEqual(oModel.get_path_from_name('aaffr'), None)
        # Test model structure
        self.assertEqual(oModel.get_path_from_name('Root'), Gtk.TreePath("0"))
        self.assertEqual(oModel.get_path_from_name('Sib'), Gtk.TreePath("1"))
        self.assertEqual(oModel.get_path_from_name('Child'),
                         Gtk.TreePath("0:0"))
        self.assertEqual(oModel.get_path_from_name('Child 2 Branch'),
                         Gtk.TreePath("0:1"))
        self.assertEqual(oModel.get_path_from_name('Card Set 1'),
                         Gtk.TreePath("0:0:1"))
        self.assertEqual(oModel.get_path_from_name('Card Set 3'),
                         Gtk.TreePath("0:0:3"))
        self.assertEqual(oModel.get_path_from_name('Child 2 Card Set 0'),
                         Gtk.TreePath("0:1:0"))
        # Test filtering
        oFilter = BaseFilters.CardSetNameFilter('Child 2')
        self.assertEqual(oModel.get_card_set_iterator(oFilter).count(), 3)
        oModel.selectfilter = oFilter
        oModel.applyfilter = True
        oModel.load()
        # Test that tree is there, with parents retained
        self.assertEqual(oModel.get_path_from_name('Root'), Gtk.TreePath("0"))
        self.assertEqual(oModel.get_path_from_name('Sib'), None)
        self.assertEqual(oModel.get_path_from_name('Child 2 Branch'),
                         Gtk.TreePath("0:0"))
        self.assertEqual(oModel.get_path_from_name('Child 2 Card Set 0'),
                         Gtk.TreePath("0:0:0"))
        oModel.applyfilter = False
        oModel.load()
        # Test that tree is restored
        self.assertEqual(oModel.get_path_from_name('Root'), Gtk.TreePath("0"))
        self.assertEqual(oModel.get_path_from_name('Sib'), Gtk.TreePath("1"))
        self.assertEqual(oModel.get_path_from_name('Child'),
                         Gtk.TreePath("0:0"))
        self.assertEqual(oModel.get_path_from_name('Child 2 Branch'),
                         Gtk.TreePath("0:1"))
        self.assertEqual(oModel.get_path_from_name('Card Set 1'),
                         Gtk.TreePath("0:0:1"))

        oFilter = BaseFilters.CardSetNameFilter('Child 2 Branch')
        self.assertEqual(oModel.get_card_set_iterator(oFilter).count(), 1)
        oModel.selectfilter = oFilter
        oModel.applyfilter = True
        oModel.load()
        # test filter results
        self.assertEqual(oModel.get_path_from_name('Root'), Gtk.TreePath("0"))
        self.assertEqual(oModel.get_path_from_name('Sib'), None)
        self.assertEqual(oModel.get_path_from_name('Child 2 Branch'),
                         Gtk.TreePath("0:0"))
        self.assertEqual(oModel.get_path_from_name('Child 2 Card Set 0'), None)
def make_set_2():
    """Make a second card set"""
    aAddedPhysCards = get_phys_cards()
    oPhysCardSet2 = PhysicalCardSet(name=CARD_SET_NAMES[1])
    oPhysCardSet2.comment = ('A formatted test comment\nA second line\n'
                             'A third line')
    oPhysCardSet2.author = 'A test author'
    oPhysCardSet2.annotations = 'Some Annotations'
    for iLoop in range(5, 10):
        # pylint: disable=no-member
        # SQLObect confused pylint
        oPhysCardSet2.addPhysicalCard(aAddedPhysCards[iLoop].id)
    for sName, sExpansion, iCount in SET_2_ONLY_CARDS:
        oPC = make_card(sName, sExpansion)
        for _iNum in range(iCount):
            # pylint: disable=no-member
            # SQLObect confused pylint
            oPhysCardSet2.addPhysicalCard(oPC.id)
    oPhysCardSet2.syncUpdate()
    return oPhysCardSet2
Exemplo n.º 25
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)
    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)
    def test_loops(self):
        """Test loop detection and loop handling"""
        # Create a loop
        oRoot = PhysicalCardSet(name='Root')
        oChild = PhysicalCardSet(name='Child', parent=oRoot)
        aChildren = []
        for iCnt in range(4):
            oSet = PhysicalCardSet(name='Card Set %d' % iCnt, parent=oChild)
            aChildren.append(oSet)
        oRoot.parent = aChildren[0]
        oRoot.syncUpdate()

        # Check that detect_loop picks this up
        self.assertTrue(detect_loop(oRoot))
        self.assertTrue(detect_loop(oChild))
        self.assertTrue(detect_loop(aChildren[0]))
        # This will also run round the loop
        self.assertTrue(detect_loop(aChildren[1]))

        # Check we identify the right cards in the loop
        aList1 = get_loop_names(oRoot)
        self.assertEqual(aList1, ['Child', 'Card Set 0', 'Root'])
        aList2 = get_loop_names(oChild)
        self.assertEqual(sorted(aList2), sorted(aList1))
        aList3 = get_loop_names(aChildren[1])
        self.assertEqual(sorted(aList3), sorted(aList1))
        # Check that deleting doesn't fix the loop, due to reparenting
        delete_physical_card_set(aChildren[0].name)
        self.assertTrue(detect_loop(oRoot))
        # Check that explicit loop breaking working
        oRoot.parent = None
        oRoot.syncUpdate()
        self.assertFalse(detect_loop(oRoot))
        self.assertFalse(detect_loop(aChildren[1]))
        aList1 = get_loop_names(oRoot)
        self.assertEqual(len(aList1), 0)
        # Create another loop
        oRoot.parent = aChildren[1]
        oRoot.syncUpdate()
        self.assertTrue(detect_loop(oRoot))
        # Use the break loop function
        self.assertEqual(break_loop(oRoot), oRoot.name)
        self.assertFalse(detect_loop(oRoot))
        self.assertFalse(detect_loop(aChildren[1]))
        # Check that break_loop returns None for non-loop status
        self.assertEqual(break_loop(oRoot), None)
        self.assertEqual(break_loop(aChildren[1]), None)
        # Try breaking loop with a child
        oRoot.parent = aChildren[1]
        oRoot.syncUpdate()
        self.assertTrue(detect_loop(oRoot))
        self.assertEqual(break_loop(aChildren[1]), aChildren[1].name)
        self.assertFalse(detect_loop(oRoot))
        self.assertFalse(detect_loop(aChildren[1]))
    def test_basic(self):
        """Test behaviour without loops"""
        oRoot = PhysicalCardSet(name='Root')
        oChild = PhysicalCardSet(name='Child', parent=oRoot)
        aChildren = []
        for iCnt in range(4):
            oSet = PhysicalCardSet(name='Card Set %d' % iCnt, parent=oChild)
            aChildren.append(oSet)
        # Check detect_loop fails
        self.assertFalse(detect_loop(oRoot))
        self.assertFalse(detect_loop(oChild))

        # Check has_children
        self.assertTrue(has_children(oRoot))
        self.assertTrue(has_children(oChild))
        self.assertFalse(has_children(aChildren[0]))
        self.assertFalse(has_children(aChildren[1]))

        # Check find_children behaves properly
        aFoundChildren = find_children(oRoot)
        self.assertEqual(len(aFoundChildren), 1)
        self.assertEqual(aFoundChildren[0].name, oChild.name)
        aFoundChildren = find_children(oChild)
        self.assertEqual(len(aFoundChildren), 4)
        self.assertEqual(sorted([x.name for x in aFoundChildren]),
                         sorted([x.name for x in aChildren]))

        # Check formatiing works
        sList = (" Root\n"
                 "    Child\n"
                 "       Card Set 0\n"
                 "       Card Set 1\n"
                 "       Card Set 2\n"
                 "       Card Set 3")
        sList2 = (" Child\n"
                  "    Card Set 0\n"
                  "    Card Set 1\n"
                  "    Card Set 2\n"
                  "    Card Set 3")
        sList3 = ("  Card Set 0\n"
                  "  Card Set 1\n"
                  "  Card Set 2\n"
                  "  Card Set 3")
        self.assertEqual(format_cs_list(None), sList)
        self.assertEqual(format_cs_list(oRoot), sList2)
        self.assertEqual(format_cs_list(oChild, '  '), sList3)

        # Check children are reparented correctly
        delete_physical_card_set(oChild.name)
        aFoundChildren = find_children(oRoot)
        self.assertEqual(len(aFoundChildren), 4)
        self.assertEqual(sorted([x.name for x in aFoundChildren]),
                         sorted([x.name for x in aChildren]))

        # Check ordinary deletion
        bRes = delete_physical_card_set(aChildren[0].name)
        self.assertEqual(bRes, True)
        aFoundChildren = find_children(oRoot)
        self.assertEqual(len(aFoundChildren), 3)
        self.assertEqual(sorted([x.name for x in aFoundChildren]),
                         sorted([x.name for x in aChildren[1:]]))

        # Check trying to delete non-existant card set
        bRes = delete_physical_card_set(aChildren[0].name)
        self.assertEqual(bRes, False)
Exemplo n.º 29
0
    def test_paste_form_card_set(self):
        """Test selecting and pasting with the different display modes"""

        # 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
        # Add card sets needed for the tests
        # pylint: disable=unsupported-membership-test, not-an-iterable
        # Checks on RelatedJoins confuse pylint

        def clear_cardset(oPCS, oFrame):
            """Clear the cards from a card set and reload the model"""
            for oCard in oPCS.cards:
                oPCS.removePhysicalCard(oCard)
            oFrame.view.get_model().load()

        oCollSet = PhysicalCardSet(name='My Collection')
        oTest1 = PhysicalCardSet(name='Test Set 1',
                                 parent=oCollSet,
                                 inuse=True)
        # Add some cards
        aCards = [('AK-47', None), ('Bronwen', 'SW'), ('Cesewayo', None),
                  ('AK-47', 'Lords of the Night'),
                  ('AK-47', 'Lords of the Night'),
                  ('Anna "Dictatrix11" Suljic', 'NoR'),
                  ('Ablative Skin', 'Sabbat')] + [('Alexandra', 'CE'),
                                                  ('Alexandra', None),
                                                  ('Ablative Skin', None)] * 5
        aPhysCards = []
        for sName, sExp in aCards:
            oCard = make_card(sName, sExp)
            aPhysCards.append(oCard)
        for oCard in aPhysCards:
            # pylint: disable=no-member
            # SQLObject confuses pylint
            oCollSet.addPhysicalCard(oCard.id)
            oCollSet.syncUpdate()
        oAKLotN = make_card(u'AK-47', u'Lords of the Night')
        oAKNone = make_card(u'AK-47', None)
        oAblative = make_card(u'Ablative Skin', None)
        oAlex = make_card(u'Alexandra', u'CE')
        for oCard in [
                oAKLotN, oAKLotN, oAKLotN, oAKNone, oAKNone,
                make_card(u'Ablative Skin', 'Sabbat'), oAblative, oAblative,
                oAblative, oAblative, oAblative, oAlex, oAlex, oAlex
        ]:
            # pylint: disable=no-member
            # SQLObject confuses pylint
            oTest1.addPhysicalCard(oCard.id)
            oTest1.syncUpdate()
        self.oWin.setup(self.oConfig)
        # Remove the unneeded panes
        for oPane in self.oWin.aOpenFrames[:]:
            if oPane.title in ('Card Text', 'Card Set List', 'Full Card List'):
                self.oWin.remove_frame(oPane)
            if oPane.title == 'My Collection':
                oMyColl = oPane
        # Create the test profile and use it to set "My Collection"
        # to 'No Children'
        self.oConfig.set_profile_option(CARDSET, "test", EXTRA_LEVEL_OPTION,
                                        "none")
        self.oConfig.set_profile(CARDSET,
                                 oMyColl.view.get_model().cardset_id, 'test')
        self.oWin.do_all_queued_reloads()
        # Create a new set to paste into
        oTest2 = PhysicalCardSet(name='Test Set 2')
        oCS2Frame = self.oWin.add_new_physical_card_set('Test Set 2', True)
        # Select 2 cards and paste them
        self._select_cards(oMyColl, [(u'AK-47', ), (u'Ablative Skin', )])
        oMyColl.view.copy_selection()
        oCS2Frame.view.do_paste()
        # 3 x AK + 6 x Ablative
        self.assertEqual(len(oTest2.cards), 9)
        # Selecting these should match the expansions in My Collection
        self.assertEqual(len([x for x in oTest2.cards if x == oAKLotN]), 2)
        self.assertEqual(len([x for x in oTest2.cards if x == oAKNone]), 1)
        self.assertEqual(len([x for x in oTest2.cards if x == oAblative]), 5)
        self.assertTrue(make_card(u'Ablative Skin', 'Sabbat') in oTest2.cards)
        # Remove cards from test card set
        clear_cardset(oTest2, oCS2Frame)
        self.assertEqual(len(oTest2.cards), 0)
        # Change mode to expansions
        self.oConfig.set_profile_option(CARDSET, "test", EXTRA_LEVEL_OPTION,
                                        "expansions")
        self.oWin.do_all_queued_reloads()
        self._select_cards(oMyColl,
                           [(u'AK-47', u'Lords of the Night'),
                            (u'Ablative Skin', ),
                            (u'Alexandra (Group 2)', u'Camarilla Edition')])
        oMyColl.view.copy_selection()
        oCS2Frame.view.do_paste()
        # 2 x AK + 6 x Ablative + 5 x Alexandra
        self.assertEqual(len(oTest2.cards), 13)
        self.assertTrue(make_card(u'Ablative Skin', 'Sabbat') in oTest2.cards)
        self.assertEqual(len([x for x in oTest2.cards if x == oAKLotN]), 2)
        self.assertEqual(len([x for x in oTest2.cards if x == oAblative]), 5)
        self.assertEqual(len([x for x in oTest2.cards if x == oAlex]), 5)
        clear_cardset(oTest2, oCS2Frame)
        self.assertEqual(len(oTest2.cards), 0)
        # Change mode to card sets
        self.oConfig.set_profile_option(CARDSET, "test", EXTRA_LEVEL_OPTION,
                                        "card sets")
        self.oWin.do_all_queued_reloads()
        oMyColl.view.get_model().load()
        self._select_cards(oMyColl, [(u'AK-47', u'Test Set 1'),
                                     (u'Ablative Skin', ),
                                     (u'Alexandra (Group 2)', u'Test Set 1')])
        oMyColl.view.copy_selection()
        oCS2Frame.view.do_paste()
        # 5 x AK + 6 x Ablative + 3 x Alexandra
        self.assertEqual(len(oTest2.cards), 14)
        self.assertTrue(make_card(u'Ablative Skin', 'Sabbat') in oTest2.cards)
        self.assertEqual(len([x for x in oTest2.cards if x == oAKLotN]), 3)
        self.assertEqual(len([x for x in oTest2.cards if x == oAKNone]), 2)
        self.assertEqual(len([x for x in oTest2.cards if x == oAblative]), 5)
        self.assertEqual(len([x for x in oTest2.cards if x == oAlex]), 3)
        clear_cardset(oTest2, oCS2Frame)
        self.assertEqual(len(oTest2.cards), 0)
        # Change mode to card sets & expansions
        self.oConfig.set_profile_option(CARDSET, "test", EXTRA_LEVEL_OPTION,
                                        "card sets then expansions")
        self.oWin.do_all_queued_reloads()
        self._select_cards(oMyColl,
                           [(u'AK-47', u'Test Set 1', u'Lords of the Night'),
                            (u'Ablative Skin', ),
                            (u'Alexandra (Group 2)', u'Test Set 1')])
        oMyColl.view.copy_selection()
        oCS2Frame.view.do_paste()
        # 3 x AK + 6 x Ablative + 3 x Alexandra
        self.assertEqual(len(oTest2.cards), 12)
        self.assertTrue(make_card(u'Ablative Skin', 'Sabbat') in oTest2.cards)
        self.assertEqual(len([x for x in oTest2.cards if x == oAKLotN]), 3)
        self.assertEqual(len([x for x in oTest2.cards if x == oAblative]), 5)
        self.assertEqual(len([x for x in oTest2.cards if x == oAlex]), 3)

        clear_cardset(oTest2, oCS2Frame)
        self.assertEqual(len(oTest2.cards), 0)
        # Change mode to expansions & card sets
        self.oConfig.set_profile_option(CARDSET, "test", EXTRA_LEVEL_OPTION,
                                        "expansions then card sets")
        self.oWin.do_all_queued_reloads()
        self._select_cards(
            oMyColl,
            [(u'AK-47', u'Lords of the Night'), (u'Ablative Skin', ),
             (u'Alexandra (Group 2)', u'Camarilla Edition', u'Test Set 1')])
        oMyColl.view.copy_selection()
        oCS2Frame.view.do_paste()
        # 2 x AK + 6 x Ablative + 3 x Alexandra
        self.assertEqual(len(oTest2.cards), 11)
        self.assertTrue(make_card(u'Ablative Skin', 'Sabbat') in oTest2.cards)
        self.assertEqual(len([x for x in oTest2.cards if x == oAKLotN]), 2)
        self.assertEqual(len([x for x in oTest2.cards if x == oAblative]), 5)
        self.assertEqual(len([x for x in oTest2.cards if x == oAlex]), 3)