Archivio

Archivio per la categoria ‘wxpython’

wx.CheckListBox: background items

8 Marzo 2011 Commenti chiusi

Quello che vorrei ottenere è una checklistbox
da un dizionario, che ordini i propri valori in base ai
valori del dizionario stesso, ma ne visualizzi le chiavi
e ne colori il background, in base ai valori.

(Che cosa inutile…..)

Il dizionario è così strutturato:

players = {u'AMBROSINI Massimo': 505, u'BENTIVOGLIO Simone': 514,
           u'ASAMOAH Kwadwo': 509, u'AMELIA Marco': 103,
           u'ANTONELLI Luca': 206, u'ARIAUDO Lorenzo': 209,
           u'ABBIATI Christian': 101,.....}

In pratica i giocatori (keys) voglio ordinarli
in base al proprio ID (value).
Se l’id è <200 si tratta di portiere,
se l'id è 200 di difensore e così via.
Vorrei colorare il giocatore nella checklistbox
e mettere in fila, portieri-difensori ecc.

Per come NON vengono ordinati i dati all’interno del dizionario,
devo ordinarli io prima di passarli alla checklistbox.
Sono sicuro ci siano metodi più eleganti e performanti, ma io
ottengo l’ordinamento per chiave così :

>>> players_ord = players.values()
>>> players_ord.sort()
>>> for value in players_ord:
	for item in players:
		if value == players.get(item):
			players_ord[players_ord.index(value)] = item

>>> print players_ord
[u'ABBIATI Christian', u'AGAZZI Micheal', u'AMELIA Marco', u'ABATE Ignazio', u'ACCARDI Pietro', u'AGOSTINI Alessandro', u'ALVAREZ Pablo Sebastian', u'ANTONELLI Luca', u'ANTONINI Luca', u'ARIAUDO Lorenzo', u'ASTORI Davide', u'ALMIRON Sergio Bernardo', u'AMBROSINI Massimo', u'ANTONELLI Filippo', u'ASAMOAH Kwadwo', u'BADU Emmanuel Agyemang', u'BARRIENTOS Pablo', u'BENTIVOGLIO Simone', u'AQUILANI Alberto', u'ADIYIAH Dominic', u'AMAURI Carvalho De Oliveira', u'BAPTISTA Julio', u'BARRETO Gonzalo', u'BERNACCI Marco', u'BOAKYE Yiaodim']

ecco che i dati sono ordinati per valore (value del dizionario) ma
con indicata la chiave.

Una volta passata la lista ordinata alla checklistbox, non resta che
colorare il background dell’item della checklistbox (chiave
del dizionario), in base al proprio valore (value del dizionario.
Questa cosa l’ho ottenuta così:

for player in self.view.clb.GetItems():
	index = (self.players_ord.index(player))
        if int(self.players.get(player)) < 200 :
            self.view.clb.SetItemBackgroundColour(index, 'yellow')
        elif int(self.players.get(player)) < 500 and int(self.players.get(player)) > 200:
            self.view.clb.SetItemBackgroundColour(index, 'pink')
        elif int(self.players.get(player)) < 800 and int(self.players.get(player)) > 500:
            self.view.clb.SetItemBackgroundColour(index, 'cyan')
        else:
            self.view.clb.SetItemBackgroundColour(index, 'white')

In pratica, invece di iterare con il “for”, la lista passata alla
checklistbox, itero direttamente sulla lista generata dal metodo
GetItems() della checklistbox, così sono sicuro di utilizzare
l’indice giusto per la colorazione del background dell’item.
Poi, siccome il valore ‘player’ del ciclo for, è anche per forza di
cose una chiave del dizionario, ne ricavo il suo valore
(metodo dict.get(k)).
Lo testo, ed in base all’esito coloro il background grazie
all’indice immagazzinato durante l’iterazione.

Senz’altro ci sono metodi migliori di questo, ma l’esito è quello che cercavo:

Come si nota nei centrocampisti (azzurri), ‘Aquilani’ viene per ultimo.
Questo è dovuto al suo valore id maggiore, dovuto ad un post-tesseramento,
ma queste sono cose da Fantacalcisti…

Ilcodice di esempio, quindi….

import wx

class CLBColorModel():
    '''Model per la consegna delle formazioni'''
    def __init__(self):
        self.players = {u'AMBROSINI Massimo': 505, u'BENTIVOGLIO Simone': 514,
                        u'ASAMOAH Kwadwo': 509, u'AMELIA Marco': 103, u'ANTONELLI Luca': 206,
                        u'ARIAUDO Lorenzo': 209, u'ABBIATI Christian': 101, u'BERNACCI Marco': 814,
                        u'ACCARDI Pietro': 202, u'AGOSTINI Alessandro': 203, u'BAPTISTA Julio': 810,
                        u'BADU Emmanuel Agyemang': 510, u'AGAZZI Micheal': 102, u'ALMIRON Sergio Bernardo': 503,
                        u'ALVAREZ Pablo Sebastian': 204, u'ADIYIAH Dominic': 803, u'ANTONINI Luca': 207,
                        u'BARRIENTOS Pablo': 512, u'ASTORI Davide': 211, u'AQUILANI Alberto': 706,
                        u'BARRETO Gonzalo': 812, u'BOAKYE Yiaodim': 816, u'ABATE Ignazio': 201,
                        u'ANTONELLI Filippo': 507, u'AMAURI Carvalho De Oliveira': 806}
    def getSortedPlayers(self):
        '''ottiene la rosa di una squadra, passandone il
        nome come parametro'''
        players_ord = self.players.values()
        players_ord.sort()
        for value in players_ord:
            for item in self.players:
                if value == self.players.get(item):
                    players_ord[players_ord.index(value)] = item
        return self.players, players_ord

class CLBColorView(wx.Frame):
    '''GUI per la creazione della squadra'''
    def __init__(self, parent):
        '''Costruttore del frame'''
        wx.Frame.__init__(self, None, -1, 'Team manager', size=(300, 500))
    def createWidgets(self, players):
        '''crea i widgets necessari alla creazione della squadra'''
        self.panel = wx.Panel(self, -1)
        self.clb = wx.CheckListBox(self.panel, -1, size = ( 200, 400 ), choices = players, style = wx.LB_HSCROLL )
        self.btn_exit = wx.Button(self.panel, wx.ID_ANY, 'Exit')
    def SizerizeWidgets(self):
        '''posiziona i vari widgets nella posizione stabilita'''
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.clb, 0, wx.ALL|wx.CENTER, 5)
        self.vbox.Add(wx.StaticLine(self.panel,), 0, wx.ALL|wx.EXPAND, 5)
        self.vbox.Add(self.btn_exit, 0, wx.CENTER)
        self.panel.SetSizer(self.vbox)
        self.Centre()
        
class CLBColorController:
    def __init__(self):
        '''Costruttore controller'''
        self.model = CLBColorModel()
        self.players, self.players_ord = self.model.getSortedPlayers()
        self.createView()

    def createView(self):
        '''crea la view e la rende visibile'''
        self.view = CLBColorView(None)
        self.view.createWidgets(self.players_ord)
        self.view.SizerizeWidgets()
        self.view.Show()
        for player in self.view.clb.GetItems():
            index = (self.players_ord.index(player)) # indice per la colorazione del player
            if int(self.players.get(player)) < 200 : # qui controllo il 'value' legato alla 'key'
                self.view.clb.SetItemBackgroundColour(index, 'yellow') #lo coloro in base al valore
            elif int(self.players.get(player)) < 500 and int(self.players.get(player)) > 200:
                self.view.clb.SetItemBackgroundColour(index, 'pink')
            elif int(self.players.get(player)) < 800 and int(self.players.get(player)) > 500:
                self.view.clb.SetItemBackgroundColour(index, 'cyan')
            else:
                self.view.clb.SetItemBackgroundColour(index, 'white')
        self.view.btn_exit.Bind(wx.EVT_BUTTON, self.onExit)
        self.view.clb.Bind(wx.EVT_CHECKLISTBOX, self.onPlayers )

    def onPlayers(self, evt):
        '''handler click checklistbox Portieri'''
        pass
    
    def onExit(self, evt):
        '''handler button di uscita'''
        self.view.Close()
        
if __name__ == '__main__':
    app = wx.App(False)
    controller = CLBColorController()
    app.MainLoop()
Categorie:wxpython Tag:

wx.CheckListBox: memorizzare stato items

1 Marzo 2011 Commenti chiusi

Mettiamo di avere una checklistbox, nella quale visualizzo,
alternativamente, tramite radiobox, due differenti serie di valori.

Il problema è quello di mantenere lo stato degli items di una lista,
quando la checklistbox, passa a visualizzare la seconda lista, e poi
torna sulla prima.

Questa cosa la si può ottenere immagazzinando nome e id degli item
selezionati in un dizionario di appoggio.
Switchando tra le 2 liste, riprenderò gli items dal dizionario
e tramite i loro id, li ri-settero’ attivi nella checklistbox,
con il metodo Check(id, True).

Di seguito il codice:

import wx

class Model:
    def __init__(self):
        self.list_a = ['a', 'b', 'c', 'd']
        self.list_b = ['e', 'f', 'g', 'h']

    def get_a(self):
        return self.list_a

    def get_b(self):
        return self.list_b
    
class View(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, None, -1, '', size=(200, 200))

    def createWidgets(self, list):
        self.panel = wx.Panel(self, -1)
        self.radiobox = wx.RadioBox(self.panel, -1, "Lists", (20, 20),
                                    wx.DefaultSize, ['a', 'b'], 1, wx.RA_SPECIFY_COLS)
        self.box = wx.CheckListBox(self.panel, -1, size = ( 100, 50 ),
                                   choices = list, style = wx.LB_HSCROLL)

    def SizerizeWidgets(self):
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.box, 1, wx.ALIGN_CENTRE)
        self.vbox.Add(self.radiobox, 1, wx.ALIGN_CENTRE)
        self.panel.SetSizer(self.vbox)
        self.Centre()
        
class Controller:
    def __init__(self, app):
        self.model = Model()
        list_a = self.model.get_a()
        self.dict_checked = {} # dizionario sul quale memorizzo i valori scelti dalla clb
        self.createView(list_a)

    def createView(self, list):
        self.list = list
        self.view = View(None)
        self.view.createWidgets(self.list)
        self.view.SizerizeWidgets()
        self.view.radiobox.Bind(wx.EVT_RADIOBOX, self.onRadioClick)
        self.view.box.Bind(wx.EVT_CHECKLISTBOX, self.onBoxClick)
        self.view.Show()

    def onRadioClick(self, evt):
        id_list = self.view.radiobox.GetSelection()
        if self.view.radiobox.GetSelection() == 0:
            list = self.model.get_a()
        else:
            list = self.model.get_b()
        self.view.box.Clear()
        self.view.box.AppendItems(list)
        # Qui controllo se ho gia' selezionato in precedenza dei valori
        # per riattivarli, switchando da una lista all'altra
        for item in self.dict_checked: #se ho un item nel diz
            if item in self.view.box.GetItems():            # lo cerco nella clb
                id = (self.view.box.GetItems()).index(item) # estrapolo l'id
                self.view.box.Check(id, True)               # riaccendo l'item nella clb
            else:
                continue                                    # salto all'item successivo del diz

    def onBoxClick(self, evt):
	# qui aggiungo l'item al diz di appoggio
        if self.view.box.IsChecked(evt.GetSelection()):
            print "%s --> selezionato" %self.view.box.GetString(evt.GetSelection())
            self.dict_checked[self.view.box.GetString(evt.GetSelection())] = \
            (self.view.box.GetItems()).index(self.view.box.GetString(evt.GetSelection()))
	# qui rimuovo l'item dal diz quando ricliccato
        else:
            print "%s --> scartato" %self.view.box.GetString(evt.GetSelection())
            self.dict_checked.pop(self.view.box.GetString(evt.GetSelection()))
    
if __name__ == '__main__':
    app = wx.App(False)
    controller = Controller(app)
    app.MainLoop()

in pratica, cliccando sul\sugli item della checklistbox, con il metodo
legato all’evento wx.EVT_CHECKLISTBOX, onBoxClick(), aggiungo al dizionario
di appoggio, il valore e l’indice corrispondente, e lo rimuovo se deselezionato.

dopo dichè, cliccando sul radio box, tramite il metodo legato all’evento
wx.EVT_RADIOBOX, onRadioClick(), controllo se, nel mio dizionario di appoggio, ci sono
elementi presenti nella lista visualizzata nella checklistbox. Se presente, lo riattivo
nella checklistbox, tramite il proprio id (immagazzinato in precedenza), con il metodo
Check(id, True).

magari non sarà un codice ultra snello, ma svolge bene il suo compito:




Categorie:wxpython Tag:

wxPython: update CheckListBox

26 Febbraio 2011 Commenti chiusi

stavo sperimentando con wx e con le checklistbox.
Il fatto di dover aggiornare il contenuto di una checklistbox, senza distruggerla per poi ricrearla, mi ha creato un po’ di problemi.
Se si ha a che fare con i sizers, nel momento in cui si ricrea la CLB per aggiornarne i contenuti, questa perde l’allineamento dato in precedenza.
Si potrebbe chiudere tutta la view, compresi frame, panel, sizers e widgets vari e poi ricrearli, ma è una soluzione orribile.

Il metodo migliore, per le mie capacità (scarsine di apprendista), rimane il metodo Clear() della CLB e l’AppendItems(NuovaListaValori) subito dopo.
Ecco un esempio, dove ho cercato di utilizzare un quasi-pattern MVC:

import wx



class Model:

    def __init__(self):
        self.list_a = ['a', 'b', 'c', 'd']
        self.list_b = ['e', 'f', 'g', 'h']

    def get_a(self):
        return self.list_a

    def get_b(self):
        return self.list_b

class View(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, None, -1, '', size=(200, 200))

    def createWidgets(self, list):
        self.panel = wx.Panel(self, -1)
        self.button = wx.Button(self.panel, 1, 'Change')
        self.box = wx.CheckListBox(self.panel, -1, size = ( 100, 50 ), choices = list, style = wx.LB_HSCROLL )

    def SizerizeWidgets(self):
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.box, 1, wx.ALIGN_CENTRE)
        self.vbox.Add(self.button, 1, wx.ALIGN_CENTRE)
        self.panel.SetSizer(self.vbox)
        self.Centre()

class Controller:

    def __init__(self, app):
        self.model = Model()
        list_a = self.model.get_a()
        self.createView(list_a)

    def createView(self, list):
        self.list = list
        self.view = View(None)
        self.view.createWidgets(self.list)
        self.view.SizerizeWidgets()
        self.view.button.Bind(wx.EVT_BUTTON, self.onClick)
        self.view.Show()

    def onClick(self, evt):
        list_b = self.model.get_b()
        self.view.box.Clear()
        self.view.box.AppendItems(list_b)

if __name__ == '__main__':

    app = wx.App(False)
    controller = Controller(app)
    app.MainLoop()

I consigli sono supergraditi.

Categorie:wxpython Tag:

wxpython: event_Skip

5 Agosto 2010 Commenti chiusi
#!/usr/bin/python

# event_skip.py

import wx

class myFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(250, 150))

        panel = MyPanel(self, -1)

        MyButton(panel, -1, 'Propaga', (15, 15))

        self.Bind(wx.EVT_BUTTON, self.OnClicked)# permetto di propagare l'evento

        self.Centre()
        self.Show(True)

    def OnClicked(self, event):
        print "l'evento ha raggiunto la classe FRAME"
        event.Skip()# permetto di propagare l'evento

class MyPanel(wx.Panel):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        self.Bind(wx.EVT_BUTTON, self.OnClicked) # permetto di propagare l'evento

    def OnClicked(self, event):
        print "l'evento ha raggiunto la classe PANEL"
        event.Skip() # permetto di propagare l'evento


class MyButton(wx.Button):
    def __init__(self, parent, id, label, pos):
        wx.Button.__init__(self, parent, id, label, pos)
        self.Bind(wx.EVT_BUTTON, self.OnClicked)

    def OnClicked(self, event):
        print "l'evento viene scatenato dalla classe BUTTON"
        event.Skip() # permetto di propagare l'evento

app = wx.App(False)
myFrame(None, -1, 'myFrame')
app.MainLoop()
Categorie:wxpython Tag:

Python: creazione calendario Fantalega

28 Aprile 2010 Commenti chiusi

Il modulo che regola la creazione del calendario secondo il metodo del cingolo a scorrimento è:

# calendar.py


class Calendar(object):
    def __init__(self, teams, rounds=2):
        self.teams = teams
        self.max_rounds = rounds
        self.team1_home = True
        self.team2_home = True
        self.matrix = []
        self.first_round_calendar = []
        self.season = []

    def generate_matrix(self):
        """
        generate_matrix() -> list

        create a matrix to fill with teams
        First init matrix with all None fields.
        The matrix first row is a copy of input iterable (i.e. teams).
        The matrix second row is the reversed one except the last iterable value
        that is excluded.
        """
        # init matrix
        self.matrix = [[None]*len(self.teams) for team in self.teams]
        # first matrix row with all teams (header) i.e. [1, 2, 3, 4]
        self.matrix[0] = self.teams
        # reversed header without the last team i.e. [3, 2, 1, None]
        row2 = self.teams[:][:-1]
        row2.reverse()
        self.matrix[1][0:(len(self.teams) - 1)] = row2[0:(len(self.teams) - 1)]

    def matrix_rotation(self):
        """
        matrix_rotation() -> list

        This is the first step of matrix composition.
        if the first row is [3, 2, 1, None], the second one will be the last value
        except None of the first row at postion 1 and then the other values rotated:
        [1, 3, 2, None]
        The last row will be [2, 1, 3, None]
        """
        i = 1
        while i < len(self.teams):
            k = 1
            for item in self.matrix[i]:
                try:
                    self.matrix[i + 1][k] = item
                    self.matrix[i + 1][0] = self.matrix[i + 1][(
                        len(self.teams) - 1)]
                    self.matrix[i + 1][(len(self.teams) - 1)] = None
                    k += 1
                except IndexError:
                    break
            i += 1

    def matrix_substitution(self):
        """
        matrix_substitution() -> list

        This is the second step of matrix composition.
        If the matrix header and a matrix row for the same index, have the same value
        the row index moves his value in place of 'None' and gets the excluded value
        of the previous matrix generation (4):
        [1, 2, 3, 4]
        [3, 2, 1, None] --> 2 has same index of header
        [3, 4, 1, 2]  4 take place of 2 and 2 substitutes None
        """
        row_m = 1
        while row_m < len(self.teams):
            for item_a in self.matrix[0]:
                for item_b in self.matrix[row_m]:
                    if self.matrix[0].index(item_a) == \
                       self.matrix[row_m].index(item_b):
                        # when a value has the same index than header 
                        if item_a == item_b:
                            # the value is substituted by the excluded one (e.g. 4)
                            self.matrix[row_m][self.matrix[row_m].index(item_b)] = \
                                self.teams[-1]  
                            self.matrix[row_m][(len(self.teams) - 1)] = item_b
            row_m += 1

    def match_composition(self):
        """
        match_composition() -> list

        Match composition: third step
        coupling the first team of header with the matrix first-row team
        with same index. The second team of header is coupled with the
        second team of the matrix first row.
        We get teams only if the team are not chosen yet, to avoid duplicated match
        if header team or n-row one is duplicate, we pass to the other column
        I.e. At day 1 we couple header team with same index first-row team,
        at day 2 we couple header team with same index second-row team and so on.
        """
        cal = []
        day = 1
        while day < len(self.teams):
            first_round = []
            for team1 in self.matrix[0]:
                index = self.matrix[0].index(team1)
                team2 = self.matrix[day][index]
                if team2 not in first_round or team1 not in first_round:
                    if self.team1_home is True:
                        first_round.append(team1)
                        first_round.append(team2)
                        cal.append((day, team1, team2))
                        self.team1_home = False
                        self.team2_home = True
                    else:
                        first_round.append(team2)
                        first_round.append(team1)
                        cal.append((day, team2, team1))
                        self.team1_home = True
                        self.team2_home = False
            day += 1
        return cal


    def generate_2nd_round(self):
        """
        generate_2nd_round() -> list

        Create the second round for half calendar
        Tuples have "day, team_a, team_b" format
        """
        return [(int(n) + len(self.teams) - 1, team2, team1)
                for n, team1, team2 in self.first_round_calendar]


    def build_season(self):
        """
        build_season() -> list

        generate a match calendar iterable.
        Tuples have "day, team_a, team_b" format
        """
        n_round = 1
        self.generate_matrix()
        self.matrix_rotation()
        self.matrix_substitution()
       
        self.first_round_calendar = self.match_composition()
        while n_round < self.max_rounds:
            second_round = self.generate_2nd_round()
            self.season = self.first_round_calendar + second_round
            n_round += 1
        return self.season

Una piccola interfaccia per l’inserimento delle squadre:

# main.py

import wx
from random import shuffle
from calendar import Calendar


def get_teams():
    app = wx.App()
    app.MainLoop()
    teams = []
    dlg = wx.TextEntryDialog(None, "number of teams?", 'INFO', '')
    if dlg.ShowModal() == wx.ID_OK:
        try:
            nteams  = int(dlg.GetValue())
        except ValueError:
            print "ERROR: Need a number!"
        else:
            # exit if number of teams is < 2
            if nteams < 2:
                print "ERROR: number of teams must be >= 2"
            else:
                
                team_no = 1
                while team_no <= nteams:
                    dlgt = wx.TextEntryDialog(None, "team name n. %d?"  % (team_no),
                                              'INFO', '')
                    if dlgt.ShowModal() == wx.ID_OK:
                        name = dlgt.GetValue()
                        if name in teams:
                            print "ERROR: team <%s> already exists" % name
                            dlgt.SetValue('')
                        else:
                            teams.append(name)
                            dlgt.SetValue('')
                            team_no += 1
                # Add fake team if number of teams is odd
                if nteams % 2 != 0: 
                    teams.append('Fake Team')
        return teams


if __name__ == '__main__':
    teams = get_teams()
    # shuffle(teams)
    if teams:
        cal = Calendar(teams=teams)
        season = cal.build_season()
        for match in season:
            print match
    else:
        print "WARNING: no teams saved"

Un piccolo abbozzo di tests:

import unittest
from calendar import Calendar


class CalendarInitTestCase(unittest.TestCase):
    def setUp(self):
        self.teams = ['Inter', 'Milan', 'Juve', 'Napoli']
        self.cal = Calendar(self.teams)

    def tearDown(self):
        self.teams = []

    def test_default_rounds(self):
        self.assertEqual(self.cal.max_rounds, 2)

    def test_default_teams(self):
        self.assertEqual(self.cal.teams, self.teams)


class CalendarMatrixTestCase(unittest.TestCase):
    def setUp(self):
        self.teams = ['Inter', 'Milan', 'Juve', 'Napoli']
        self.cal = Calendar(self.teams)
        self.cal.generate_matrix()

    def tearDown(self):
        self.cal.teams = []
        self.cal.matrix = []

    def test_matrix_header(self):
        self.assertEqual(self.cal.matrix[0], self.teams)

    def test_matrix_first_row_before_rotation(self):
        self.assertEqual(self.cal.matrix[1], ['Juve', 'Milan', 'Inter', None])

    def test_matrix_second_row_before_rotation(self):
        self.assertEqual(self.cal.matrix[2], [None, None, None, None])

    def test_matrix_third_row_before_rotation(self):
        self.assertEqual(self.cal.matrix[3], [None, None, None, None])

    def test_matrix_second_row_after_rotation(self):
        self.cal.matrix_rotation()
        self.assertEqual(self.cal.matrix[2], ['Inter', 'Juve', 'Milan', None])

    def test_matrix_third_row_after_rotation(self):
        self.cal.matrix_rotation()
        self.assertEqual(self.cal.matrix[3], ['Milan', 'Inter', 'Juve', None])

    def test_matrix_first_row_after_substitution(self):
        self.cal.matrix_rotation()
        self.cal.matrix_substitution()
        self.assertEqual(self.cal.matrix[1], ['Juve', 'Napoli', 'Inter', 'Milan'])

    def test_matrix_second_row_after_substitution(self):
        self.cal.matrix_rotation()
        self.cal.matrix_substitution()
        self.assertEqual(self.cal.matrix[2], ['Napoli', 'Juve', 'Milan', 'Inter'])

    def test_matrix_third_row_after_substitution(self):
        self.cal.matrix_rotation()
        self.cal.matrix_substitution()
        self.assertEqual(self.cal.matrix[3], ['Milan', 'Inter', 'Napoli', 'Juve'])


class CalendarSeasonTestCase(unittest.TestCase):
    def setUp(self):
        self.teams = ['Inter', 'Milan', 'Juve', 'Napoli']
        self.cal = Calendar(self.teams)
        self.cal.generate_matrix()
        self.cal.matrix_rotation()
        self.cal.matrix_substitution()
        self.season = [(1, 'Inter', 'Juve'), (1, 'Napoli', 'Milan'),
                       (2, 'Inter', 'Napoli'), (2, 'Juve', 'Milan'),
                       (3, 'Inter', 'Milan'), (3, 'Napoli', 'Juve'),
                       (4, u'Juve', u'Inter'), (4, u'Milan', u'Napoli'),
                       (5, u'Napoli', u'Inter'), (5, u'Milan', u'Juve'),
                       (6, u'Milan', u'Inter'), (6, u'Juve', u'Napoli')]
    def tearDown(self):
        self.cal.teams = []
        self.cal.matrix = []

    def test_1st_round_season(self):
        self.cal.build_season()
        self.assertEqual(self.cal.first_round_calendar,
                         self.season[:len(self.season)/2])

    def test_complete_season(self):
        self.cal.build_season()
        self.assertEqual(self.cal.season, self.season)
        
        
    


if __name__ == '__main__':
    suite1 = unittest.TestLoader().loadTestsFromTestCase(CalendarInitTestCase)
    suite2 = unittest.TestLoader().loadTestsFromTestCase(CalendarMatrixTestCase)
    suite3 = unittest.TestLoader().loadTestsFromTestCase(CalendarSeasonTestCase)
    alltests = unittest.TestSuite([suite1, suite2, suite3])
    unittest.TextTestRunner(verbosity=2).run(alltests)
Categorie:python, wxpython Tag: ,