~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/database.py

Modified the database so that exercises are now stored in the database, rather
than in flat files.

This also necessitated adding new tables and storm classes for test suites
and test cases.

Note that this commit merely changes the database and adds a script to
upload exercises. The code for actually reading exercises has yet
to be changed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
# Author: Matt Giuca, Will Grant
19
19
 
20
 
"""Database utilities and content classes.
 
20
"""
 
21
Database Classes and Utilities for Storm ORM
21
22
 
22
23
This module provides all of the classes which map to database tables.
23
24
It also provides miscellaneous utility functions for database interaction.
24
25
"""
25
26
 
26
 
import hashlib
 
27
import md5
27
28
import datetime
28
29
 
29
30
from storm.locals import create_database, Store, Int, Unicode, DateTime, \
30
31
                         Reference, ReferenceSet, Bool, Storm, Desc
31
 
from storm.expr import Select, Max
32
 
from storm.exceptions import NotOneError, IntegrityError
33
32
 
34
 
from ivle.worksheet.rst import rst
 
33
import ivle.conf
 
34
import ivle.caps
35
35
 
36
36
__all__ = ['get_store',
37
37
            'User',
38
38
            'Subject', 'Semester', 'Offering', 'Enrolment',
39
39
            'ProjectSet', 'Project', 'ProjectGroup', 'ProjectGroupMembership',
40
 
            'Assessed', 'ProjectSubmission', 'ProjectExtension',
41
40
            'Exercise', 'Worksheet', 'WorksheetExercise',
42
41
            'ExerciseSave', 'ExerciseAttempt',
43
 
            'TestCase', 'TestSuite', 'TestSuiteVar'
 
42
            'AlreadyEnrolledError', 'TestCase', 'TestSuite'
44
43
        ]
45
44
 
46
45
def _kwarg_init(self, **kwargs):
50
49
                % (self.__class__.__name__, k))
51
50
        setattr(self, k, v)
52
51
 
53
 
def get_conn_string(config):
54
 
    """Create a Storm connection string to the IVLE database
55
 
 
56
 
    @param config: The IVLE configuration.
57
 
    """
58
 
 
59
 
    clusterstr = ''
60
 
    if config['database']['username']:
61
 
        clusterstr += config['database']['username']
62
 
        if config['database']['password']:
63
 
            clusterstr += ':' + config['database']['password']
64
 
        clusterstr += '@'
65
 
 
66
 
    host = config['database']['host'] or 'localhost'
67
 
    port = config['database']['port'] or 5432
68
 
 
69
 
    clusterstr += '%s:%d' % (host, port)
70
 
 
71
 
    return "postgres://%s/%s" % (clusterstr, config['database']['name'])
72
 
 
73
 
def get_store(config):
74
 
    """Create a Storm store connected to the IVLE database.
75
 
 
76
 
    @param config: The IVLE configuration.
77
 
    """
78
 
    return Store(create_database(get_conn_string(config)))
 
52
def get_conn_string():
 
53
    """
 
54
    Returns the Storm connection string, generated from the conf file.
 
55
    """
 
56
    return "postgres://%s:%s@%s:%d/%s" % (ivle.conf.db_user,
 
57
        ivle.conf.db_password, ivle.conf.db_host, ivle.conf.db_port,
 
58
        ivle.conf.db_dbname)
 
59
 
 
60
def get_store():
 
61
    """
 
62
    Open a database connection and transaction. Return a storm.store.Store
 
63
    instance connected to the configured IVLE database.
 
64
    """
 
65
    return Store(create_database(get_conn_string()))
79
66
 
80
67
# USERS #
81
68
 
82
69
class User(Storm):
83
 
    """An IVLE user account."""
 
70
    """
 
71
    Represents an IVLE user.
 
72
    """
84
73
    __storm_table__ = "login"
85
74
 
86
75
    id = Int(primary=True, name="loginid")
87
76
    login = Unicode()
88
77
    passhash = Unicode()
89
78
    state = Unicode()
90
 
    admin = Bool()
 
79
    rolenm = Unicode()
91
80
    unixid = Int()
92
81
    nick = Unicode()
93
82
    pass_exp = DateTime()
99
88
    studentid = Unicode()
100
89
    settings = Unicode()
101
90
 
 
91
    def _get_role(self):
 
92
        if self.rolenm is None:
 
93
            return None
 
94
        return ivle.caps.Role(self.rolenm)
 
95
    def _set_role(self, value):
 
96
        if not isinstance(value, ivle.caps.Role):
 
97
            raise TypeError("role must be an ivle.caps.Role")
 
98
        self.rolenm = unicode(value)
 
99
    role = property(_get_role, _set_role)
 
100
 
102
101
    __init__ = _kwarg_init
103
102
 
104
103
    def __repr__(self):
115
114
            return None
116
115
        return self.hash_password(password) == self.passhash
117
116
 
118
 
    @property
119
 
    def display_name(self):
120
 
        return self.fullname
 
117
    def hasCap(self, capability):
 
118
        """Given a capability (which is a Role object), returns True if this
 
119
        User has that capability, False otherwise.
 
120
        """
 
121
        return self.role.hasCap(capability)
121
122
 
122
123
    @property
123
124
    def password_expired(self):
129
130
        fieldval = self.acct_exp
130
131
        return fieldval is not None and datetime.datetime.now() > fieldval
131
132
 
132
 
    @property
133
 
    def valid(self):
134
 
        return self.state == 'enabled' and not self.account_expired
135
 
 
136
133
    def _get_enrolments(self, justactive):
137
134
        return Store.of(self).find(Enrolment,
138
135
            Enrolment.user_id == self.id,
162
159
 
163
160
    # TODO: Invitations should be listed too?
164
161
    def get_groups(self, offering=None):
165
 
        """Get groups of which this user is a member.
166
 
 
167
 
        @param offering: An optional offering to restrict the search to.
168
 
        """
169
162
        preds = [
170
163
            ProjectGroupMembership.user_id == self.id,
171
164
            ProjectGroup.id == ProjectGroupMembership.project_group_id,
191
184
        '''A sanely ordered list of all of the user's enrolments.'''
192
185
        return self._get_enrolments(False) 
193
186
 
194
 
    def get_projects(self, offering=None, active_only=True):
195
 
        """Find projects that the user can submit.
196
 
 
197
 
        This will include projects for offerings in which the user is
198
 
        enrolled, as long as the project is not in a project set which has
199
 
        groups (ie. if maximum number of group members is 0).
200
 
 
201
 
        @param active_only: Whether to only search active offerings.
202
 
        @param offering: An optional offering to restrict the search to.
203
 
        """
204
 
        return Store.of(self).find(Project,
205
 
            Project.project_set_id == ProjectSet.id,
206
 
            ProjectSet.max_students_per_group == None,
207
 
            ProjectSet.offering_id == Offering.id,
208
 
            (offering is None) or (Offering.id == offering.id),
209
 
            Semester.id == Offering.semester_id,
210
 
            (not active_only) or (Semester.state == u'current'),
211
 
            Enrolment.offering_id == Offering.id,
212
 
            Enrolment.user_id == self.id)
213
 
 
214
187
    @staticmethod
215
188
    def hash_password(password):
216
 
        """Hash a password with MD5."""
217
 
        return hashlib.md5(password).hexdigest()
 
189
        return md5.md5(password).hexdigest()
218
190
 
219
191
    @classmethod
220
192
    def get_by_login(cls, store, login):
221
 
        """Find a user in a store by login name."""
 
193
        """
 
194
        Get the User from the db associated with a given store and
 
195
        login.
 
196
        """
222
197
        return store.find(cls, cls.login == unicode(login)).one()
223
198
 
224
199
    def get_permissions(self, user):
225
 
        """Determine privileges held by a user over this object.
226
 
 
227
 
        If the user requesting privileges is this user or an admin,
228
 
        they may do everything. Otherwise they may do nothing.
229
 
        """
230
 
        if user and user.admin or user is self:
231
 
            return set(['view', 'edit', 'submit_project'])
 
200
        if user and user.rolenm == 'admin' or user is self:
 
201
            return set(['view', 'edit'])
232
202
        else:
233
203
            return set()
234
204
 
235
205
# SUBJECTS AND ENROLMENTS #
236
206
 
237
207
class Subject(Storm):
238
 
    """A subject (or course) which is run in some semesters."""
239
 
 
240
208
    __storm_table__ = "subject"
241
209
 
242
210
    id = Int(primary=True, name="subjectid")
253
221
        return "<%s '%s'>" % (type(self).__name__, self.short_name)
254
222
 
255
223
    def get_permissions(self, user):
256
 
        """Determine privileges held by a user over this object.
257
 
 
258
 
        If the user requesting privileges is an admin, they may edit.
259
 
        Otherwise they may only read.
260
 
        """
261
224
        perms = set()
262
225
        if user is not None:
263
226
            perms.add('view')
264
 
            if user.admin:
265
 
                perms.add('edit')
 
227
        if user.rolenm == 'admin':
 
228
            perms.add('edit')
266
229
        return perms
267
230
 
268
 
    def active_offerings(self):
269
 
        """Find active offerings for this subject.
270
 
 
271
 
        Return a sequence of currently active offerings for this subject
272
 
        (offerings whose semester.state is "current"). There should be 0 or 1
273
 
        elements in this sequence, but it's possible there are more.
274
 
        """
275
 
        return self.offerings.find(Offering.semester_id == Semester.id,
276
 
                                   Semester.state == u'current')
277
 
 
278
 
    def offering_for_semester(self, year, semester):
279
 
        """Get the offering for the given year/semester, or None.
280
 
 
281
 
        @param year: A string representation of the year.
282
 
        @param semester: A string representation of the semester.
283
 
        """
284
 
        return self.offerings.find(Offering.semester_id == Semester.id,
285
 
                               Semester.year == unicode(year),
286
 
                               Semester.semester == unicode(semester)).one()
287
 
 
288
231
class Semester(Storm):
289
 
    """A semester in which subjects can be run."""
290
 
 
291
232
    __storm_table__ = "semester"
292
233
 
293
234
    id = Int(primary=True, name="semesterid")
294
235
    year = Unicode()
295
236
    semester = Unicode()
296
 
    state = Unicode()
 
237
    active = Bool()
297
238
 
298
239
    offerings = ReferenceSet(id, 'Offering.semester_id')
299
 
    enrolments = ReferenceSet(id,
300
 
                              'Offering.semester_id',
301
 
                              'Offering.id',
302
 
                              'Enrolment.offering_id')
303
240
 
304
241
    __init__ = _kwarg_init
305
242
 
307
244
        return "<%s %s/%s>" % (type(self).__name__, self.year, self.semester)
308
245
 
309
246
class Offering(Storm):
310
 
    """An offering of a subject in a particular semester."""
311
 
 
312
247
    __storm_table__ = "offering"
313
248
 
314
249
    id = Int(primary=True, name="offeringid")
325
260
                           'User.id')
326
261
    project_sets = ReferenceSet(id, 'ProjectSet.offering_id')
327
262
 
328
 
    worksheets = ReferenceSet(id, 
329
 
        'Worksheet.offering_id', 
330
 
        order_by="seq_no"
331
 
    )
 
263
    worksheets = ReferenceSet(id, 'Worksheet.offering_id')
332
264
 
333
265
    __init__ = _kwarg_init
334
266
 
336
268
        return "<%s %r in %r>" % (type(self).__name__, self.subject,
337
269
                                  self.semester)
338
270
 
339
 
    def enrol(self, user, role=u'student'):
340
 
        """Enrol a user in this offering.
341
 
 
342
 
        Enrolments handle both the staff and student cases. The role controls
343
 
        the privileges granted by this enrolment.
344
 
        """
345
 
        enrolment = Store.of(self).find(Enrolment,
346
 
                               Enrolment.user_id == user.id,
347
 
                               Enrolment.offering_id == self.id).one()
348
 
 
349
 
        if enrolment is None:
350
 
            enrolment = Enrolment(user=user, offering=self)
351
 
            self.enrolments.add(enrolment)
352
 
 
353
 
        enrolment.active = True
354
 
        enrolment.role = role
355
 
 
356
 
    def unenrol(self, user):
357
 
        '''Unenrol a user from this offering.'''
358
 
        enrolment = Store.of(self).find(Enrolment,
359
 
                               Enrolment.user_id == user.id,
360
 
                               Enrolment.offering_id == self.id).one()
361
 
        Store.of(enrolment).remove(enrolment)
362
 
 
363
 
    def get_permissions(self, user):
364
 
        perms = set()
365
 
        if user is not None:
366
 
            enrolment = self.get_enrolment(user)
367
 
            if enrolment or user.admin:
368
 
                perms.add('view')
369
 
            if (enrolment and enrolment.role in (u'tutor', u'lecturer')) \
370
 
               or user.admin:
371
 
                perms.add('edit')
372
 
        return perms
373
 
 
374
 
    def get_enrolment(self, user):
375
 
        """Find the user's enrolment in this offering."""
376
 
        try:
377
 
            enrolment = self.enrolments.find(user=user).one()
378
 
        except NotOneError:
379
 
            enrolment = None
380
 
 
381
 
        return enrolment
382
 
 
383
 
    def get_members_by_role(self, role):
384
 
        return Store.of(self).find(User,
385
 
                Enrolment.user_id == User.id,
386
 
                Enrolment.offering_id == self.id,
387
 
                Enrolment.role == role
388
 
                )
389
 
 
390
 
    @property
391
 
    def students(self):
392
 
        return self.get_members_by_role(u'student')
 
271
    def enrol(self, user):
 
272
        '''Enrol a user in this offering.'''
 
273
        # We'll get a horrible database constraint violation error if we try
 
274
        # to add a second enrolment.
 
275
        if Store.of(self).find(Enrolment,
 
276
                               Enrolment.user_id == user.id,
 
277
                               Enrolment.offering_id == self.id).count() == 1:
 
278
            raise AlreadyEnrolledError()
 
279
 
 
280
        e = Enrolment(user=user, offering=self, active=True)
 
281
        self.enrolments.add(e)
393
282
 
394
283
class Enrolment(Storm):
395
 
    """An enrolment of a user in an offering.
396
 
 
397
 
    This represents the roles of both staff and students.
398
 
    """
399
 
 
400
284
    __storm_table__ = "enrolment"
401
285
    __storm_primary__ = "user_id", "offering_id"
402
286
 
404
288
    user = Reference(user_id, User.id)
405
289
    offering_id = Int(name="offeringid")
406
290
    offering = Reference(offering_id, Offering.id)
407
 
    role = Unicode()
408
291
    notes = Unicode()
409
292
    active = Bool()
410
293
 
422
305
        return "<%s %r in %r>" % (type(self).__name__, self.user,
423
306
                                  self.offering)
424
307
 
 
308
class AlreadyEnrolledError(Exception):
 
309
    pass
 
310
 
425
311
# PROJECTS #
426
312
 
427
313
class ProjectSet(Storm):
428
 
    """A set of projects that share common groups.
429
 
 
430
 
    Each student project group is attached to a project set. The group is
431
 
    valid for all projects in the group's set.
432
 
    """
433
 
 
434
314
    __storm_table__ = "project_set"
435
315
 
436
316
    id = Int(name="projectsetid", primary=True)
447
327
        return "<%s %d in %r>" % (type(self).__name__, self.id,
448
328
                                  self.offering)
449
329
 
450
 
    def get_permissions(self, user):
451
 
        return self.offering.get_permissions(user)
452
 
 
453
 
    @property
454
 
    def assigned(self):
455
 
        """Get the entities (groups or users) assigned to submit this project.
456
 
 
457
 
        This will be a Storm ResultSet.
458
 
        """
459
 
        #If its a solo project, return everyone in offering
460
 
        if self.max_students_per_group is None:
461
 
            return self.offering.students
462
 
        else:
463
 
            return self.project_groups
464
 
 
465
330
class Project(Storm):
466
 
    """A student project for which submissions can be made."""
467
 
 
468
331
    __storm_table__ = "project"
469
332
 
470
333
    id = Int(name="projectid", primary=True)
471
 
    name = Unicode()
472
 
    short_name = Unicode()
473
334
    synopsis = Unicode()
474
335
    url = Unicode()
475
336
    project_set_id = Int(name="projectsetid")
476
337
    project_set = Reference(project_set_id, ProjectSet.id)
477
338
    deadline = DateTime()
478
339
 
479
 
    assesseds = ReferenceSet(id, 'Assessed.project_id')
480
 
    submissions = ReferenceSet(id,
481
 
                               'Assessed.project_id',
482
 
                               'Assessed.id',
483
 
                               'ProjectSubmission.assessed_id')
484
 
 
485
340
    __init__ = _kwarg_init
486
341
 
487
342
    def __repr__(self):
488
 
        return "<%s '%s' in %r>" % (type(self).__name__, self.short_name,
 
343
        return "<%s '%s' in %r>" % (type(self).__name__, self.synopsis,
489
344
                                  self.project_set.offering)
490
345
 
491
 
    def can_submit(self, principal):
492
 
        return (self in principal.get_projects() and
493
 
                self.deadline > datetime.datetime.now())
494
 
 
495
 
    def submit(self, principal, path, revision, who):
496
 
        """Submit a Subversion path and revision to a project.
497
 
 
498
 
        @param principal: The owner of the Subversion repository, and the
499
 
                          entity on behalf of whom the submission is being made
500
 
        @param path: A path within that repository to submit.
501
 
        @param revision: The revision of that path to submit.
502
 
        @param who: The user who is actually making the submission.
503
 
        """
504
 
 
505
 
        if not self.can_submit(principal):
506
 
            raise Exception('cannot submit')
507
 
 
508
 
        a = Assessed.get(Store.of(self), principal, self)
509
 
        ps = ProjectSubmission()
510
 
        ps.path = path
511
 
        ps.revision = revision
512
 
        ps.date_submitted = datetime.datetime.now()
513
 
        ps.assessed = a
514
 
        ps.submitter = who
515
 
 
516
 
        return ps
517
 
 
518
 
    def get_permissions(self, user):
519
 
        return self.project_set.offering.get_permissions(user)
520
 
 
521
 
    @property
522
 
    def latest_submissions(self):
523
 
        """Return the latest submission for each Assessed."""
524
 
        return Store.of(self).find(ProjectSubmission,
525
 
            Assessed.project_id == self.id,
526
 
            ProjectSubmission.assessed_id == Assessed.id,
527
 
            ProjectSubmission.date_submitted == Select(
528
 
                    Max(ProjectSubmission.date_submitted),
529
 
                    ProjectSubmission.assessed_id == Assessed.id,
530
 
                    tables=ProjectSubmission
531
 
            )
532
 
        )
533
 
 
534
 
 
535
346
class ProjectGroup(Storm):
536
 
    """A group of students working together on a project."""
537
 
 
538
347
    __storm_table__ = "project_group"
539
348
 
540
349
    id = Int(name="groupid", primary=True)
557
366
        return "<%s %s in %r>" % (type(self).__name__, self.name,
558
367
                                  self.project_set.offering)
559
368
 
560
 
    @property
561
 
    def display_name(self):
562
 
        return '%s (%s)' % (self.nick, self.name)
563
 
 
564
 
    def get_projects(self, offering=None, active_only=True):
565
 
        '''Find projects that the group can submit.
566
 
 
567
 
        This will include projects in the project set which owns this group,
568
 
        unless the project set disallows groups (in which case none will be
569
 
        returned).
570
 
 
571
 
        @param active_only: Whether to only search active offerings.
572
 
        @param offering: An optional offering to restrict the search to.
573
 
        '''
574
 
        return Store.of(self).find(Project,
575
 
            Project.project_set_id == ProjectSet.id,
576
 
            ProjectSet.id == self.project_set.id,
577
 
            ProjectSet.max_students_per_group != None,
578
 
            ProjectSet.offering_id == Offering.id,
579
 
            (offering is None) or (Offering.id == offering.id),
580
 
            Semester.id == Offering.semester_id,
581
 
            (not active_only) or (Semester.state == u'current'))
582
 
 
583
 
 
584
 
    def get_permissions(self, user):
585
 
        if user.admin or user in self.members:
586
 
            return set(['submit_project'])
587
 
        else:
588
 
            return set()
589
 
 
590
369
class ProjectGroupMembership(Storm):
591
 
    """A student's membership in a project group."""
592
 
 
593
370
    __storm_table__ = "group_member"
594
371
    __storm_primary__ = "user_id", "project_group_id"
595
372
 
604
381
        return "<%s %r in %r>" % (type(self).__name__, self.user,
605
382
                                  self.project_group)
606
383
 
607
 
class Assessed(Storm):
608
 
    """A composite of a user or group combined with a project.
609
 
 
610
 
    Each project submission and extension refers to an Assessed. It is the
611
 
    sole specifier of the repository and project.
612
 
    """
613
 
 
614
 
    __storm_table__ = "assessed"
615
 
 
616
 
    id = Int(name="assessedid", primary=True)
617
 
    user_id = Int(name="loginid")
618
 
    user = Reference(user_id, User.id)
619
 
    project_group_id = Int(name="groupid")
620
 
    project_group = Reference(project_group_id, ProjectGroup.id)
621
 
 
622
 
    project_id = Int(name="projectid")
623
 
    project = Reference(project_id, Project.id)
624
 
 
625
 
    extensions = ReferenceSet(id, 'ProjectExtension.assessed_id')
626
 
    submissions = ReferenceSet(id, 'ProjectSubmission.assessed_id')
627
 
 
628
 
    def __repr__(self):
629
 
        return "<%s %r in %r>" % (type(self).__name__,
630
 
            self.user or self.project_group, self.project)
631
 
 
632
 
    @property
633
 
    def is_group(self):
634
 
        """True if the Assessed is a group, False if it is a user."""
635
 
        return self.project_group is not None
636
 
 
637
 
    @property
638
 
    def principal(self):
639
 
        return self.project_group or self.user
640
 
 
641
 
    @classmethod
642
 
    def get(cls, store, principal, project):
643
 
        """Find or create an Assessed for the given user or group and project.
644
 
 
645
 
        @param principal: The user or group.
646
 
        @param project: The project.
647
 
        """
648
 
        t = type(principal)
649
 
        if t not in (User, ProjectGroup):
650
 
            raise AssertionError('principal must be User or ProjectGroup')
651
 
 
652
 
        a = store.find(cls,
653
 
            (t is User) or (cls.project_group_id == principal.id),
654
 
            (t is ProjectGroup) or (cls.user_id == principal.id),
655
 
            Project.id == project.id).one()
656
 
 
657
 
        if a is None:
658
 
            a = cls()
659
 
            if t is User:
660
 
                a.user = principal
661
 
            else:
662
 
                a.project_group = principal
663
 
            a.project = project
664
 
            store.add(a)
665
 
 
666
 
        return a
667
 
 
668
 
 
669
 
class ProjectExtension(Storm):
670
 
    """An extension granted to a user or group on a particular project.
671
 
 
672
 
    The user or group and project are specified by the Assessed.
673
 
    """
674
 
 
675
 
    __storm_table__ = "project_extension"
676
 
 
677
 
    id = Int(name="extensionid", primary=True)
678
 
    assessed_id = Int(name="assessedid")
679
 
    assessed = Reference(assessed_id, Assessed.id)
680
 
    deadline = DateTime()
681
 
    approver_id = Int(name="approver")
682
 
    approver = Reference(approver_id, User.id)
683
 
    notes = Unicode()
684
 
 
685
 
class ProjectSubmission(Storm):
686
 
    """A submission from a user or group repository to a particular project.
687
 
 
688
 
    The content of a submission is a single path and revision inside a
689
 
    repository. The repository is that owned by the submission's user and
690
 
    group, while the path and revision are explicit.
691
 
 
692
 
    The user or group and project are specified by the Assessed.
693
 
    """
694
 
 
695
 
    __storm_table__ = "project_submission"
696
 
 
697
 
    id = Int(name="submissionid", primary=True)
698
 
    assessed_id = Int(name="assessedid")
699
 
    assessed = Reference(assessed_id, Assessed.id)
700
 
    path = Unicode()
701
 
    revision = Int()
702
 
    submitter_id = Int(name="submitter")
703
 
    submitter = Reference(submitter_id, User.id)
704
 
    date_submitted = DateTime()
705
 
 
706
 
 
707
384
# WORKSHEETS AND EXERCISES #
708
385
 
709
386
class Exercise(Storm):
710
 
    """An exercise for students to complete in a worksheet.
711
 
 
712
 
    An exercise may be present in any number of worksheets.
713
 
    """
714
 
 
715
 
    __storm_table__ = "exercise"
 
387
    # Note: Table "problem" is called "Exercise" in the Object layer, since
 
388
    # it's called that everywhere else.
 
389
    __storm_table__ = "problem"
 
390
#TODO: Add in a field for the user-friendly identifier
716
391
    id = Unicode(primary=True, name="identifier")
717
392
    name = Unicode()
718
393
    description = Unicode()
721
396
    include = Unicode()
722
397
    num_rows = Int()
723
398
 
724
 
    worksheet_exercises =  ReferenceSet(id,
725
 
        'WorksheetExercise.exercise_id')
726
 
 
727
399
    worksheets = ReferenceSet(id,
728
400
        'WorksheetExercise.exercise_id',
729
401
        'WorksheetExercise.worksheet_id',
730
402
        'Worksheet.id'
731
403
    )
732
 
 
733
 
    test_suites = ReferenceSet(id, 
734
 
        'TestSuite.exercise_id',
735
 
        order_by='seq_no')
 
404
    
 
405
    test_suites = ReferenceSet(id, 'TestSuite.exercise_id')
736
406
 
737
407
    __init__ = _kwarg_init
738
408
 
739
409
    def __repr__(self):
740
410
        return "<%s %s>" % (type(self).__name__, self.name)
741
411
 
742
 
    def get_permissions(self, user):
743
 
        perms = set()
744
 
        roles = set()
745
 
        if user is not None:
746
 
            if user.admin:
747
 
                perms.add('edit')
748
 
                perms.add('view')
749
 
            elif u'lecturer' in set((e.role for e in user.active_enrolments)):
750
 
                perms.add('edit')
751
 
                perms.add('view')
752
 
            elif u'tutor' in set((e.role for e in user.active_enrolments)):
753
 
                perms.add('edit')
754
 
                perms.add('view')
755
 
 
756
 
        return perms
757
 
 
758
 
    def get_description(self):
759
 
        """Return the description interpreted as reStructuredText."""
760
 
        return rst(self.description)
761
 
 
762
 
    def delete(self):
763
 
        """Deletes the exercise, providing it has no associated worksheets."""
764
 
        if (self.worksheet_exercises.count() > 0):
765
 
            raise IntegrityError()
766
 
        for suite in self.test_suites:
767
 
            suite.delete()
768
 
        Store.of(self).remove(self)
 
412
    @classmethod
 
413
    def get_by_name(cls, store, name):
 
414
        """
 
415
        Get the Exercise from the db associated with a given store and name.
 
416
        If the exercise is not in the database, creates it and inserts it
 
417
        automatically.
 
418
        """
 
419
        ex = store.find(cls, cls.name == unicode(name)).one()
 
420
        if ex is not None:
 
421
            return ex
 
422
        ex = Exercise(name=unicode(name))
 
423
        store.add(ex)
 
424
        store.commit()
 
425
        return ex
769
426
 
770
427
class Worksheet(Storm):
771
 
    """A worksheet with exercises for students to complete.
772
 
 
773
 
    Worksheets are owned by offerings.
774
 
    """
775
 
 
776
428
    __storm_table__ = "worksheet"
777
429
 
778
430
    id = Int(primary=True, name="worksheetid")
 
431
    # XXX subject is not linked to a Subject object. This is a property of
 
432
    # the database, and will be refactored.
 
433
    subject = Unicode()
779
434
    offering_id = Int(name="offeringid")
780
 
    identifier = Unicode()
781
 
    name = Unicode()
 
435
    name = Unicode(name="identifier")
782
436
    assessable = Bool()
783
 
    data = Unicode()
784
 
    seq_no = Int()
785
 
    format = Unicode()
786
 
 
787
 
    attempts = ReferenceSet(id, "ExerciseAttempt.worksheetid")
788
 
    offering = Reference(offering_id, 'Offering.id')
789
 
 
790
 
    all_worksheet_exercises = ReferenceSet(id,
 
437
    mtime = DateTime()
 
438
 
 
439
    offering = Reference (offeringid, 'Offering.id')
 
440
 
 
441
    exercises = ReferenceSet(id,
 
442
        'WorksheetExercise.worksheet_id',
 
443
        'WorksheetExercise.exercise_id',
 
444
        Exercise.id)
 
445
    # Use worksheet_exercises to get access to the WorksheetExercise objects
 
446
    # binding worksheets to exercises. This is required to access the
 
447
    # "optional" field.
 
448
    worksheet_exercises = ReferenceSet(id,
791
449
        'WorksheetExercise.worksheet_id')
792
 
 
793
 
    # Use worksheet_exercises to get access to the *active* WorksheetExercise
794
 
    # objects binding worksheets to exercises. This is required to access the
795
 
    # "optional" field.
796
 
 
797
 
    @property
798
 
    def worksheet_exercises(self):
799
 
        return self.all_worksheet_exercises.find(active=True)
 
450
        
800
451
 
801
452
    __init__ = _kwarg_init
802
453
 
803
454
    def __repr__(self):
804
455
        return "<%s %s>" % (type(self).__name__, self.name)
805
456
 
806
 
    def remove_all_exercises(self):
807
 
        """Remove all exercises from this worksheet.
 
457
    # XXX Refactor this - make it an instance method of Subject rather than a
 
458
    # class method of Worksheet. Can't do that now because Subject isn't
 
459
    # linked referentially to the Worksheet.
 
460
    @classmethod
 
461
    def get_by_name(cls, store, subjectname, worksheetname):
 
462
        """
 
463
        Get the Worksheet from the db associated with a given store, subject
 
464
        name and worksheet name.
 
465
        """
 
466
        return store.find(cls, cls.subject == unicode(subjectname),
 
467
            cls.name == unicode(worksheetname)).one()
808
468
 
 
469
    def remove_all_exercises(self, store):
 
470
        """
 
471
        Remove all exercises from this worksheet.
809
472
        This does not delete the exercises themselves. It just removes them
810
473
        from the worksheet.
811
474
        """
812
 
        store = Store.of(self)
813
 
        for ws_ex in self.all_worksheet_exercises:
814
 
            if ws_ex.saves.count() > 0 or ws_ex.attempts.count() > 0:
815
 
                raise IntegrityError()
816
475
        store.find(WorksheetExercise,
817
476
            WorksheetExercise.worksheet == self).remove()
818
477
 
819
 
    def get_permissions(self, user):
820
 
        return self.offering.get_permissions(user)
821
 
 
822
 
    def get_xml(self):
823
 
        """Returns the xml of this worksheet, converts from rst if required."""
824
 
        if self.format == u'rst':
825
 
            ws_xml = rst(self.data)
826
 
            return ws_xml
827
 
        else:
828
 
            return self.data
829
 
 
830
 
    def delete(self):
831
 
        """Deletes the worksheet, provided it has no attempts on any exercises.
832
 
 
833
 
        Returns True if delete succeeded, or False if this worksheet has
834
 
        attempts attached."""
835
 
        for ws_ex in self.all_worksheet_exercises:
836
 
            if ws_ex.saves.count() > 0 or ws_ex.attempts.count() > 0:
837
 
                raise IntegrityError()
838
 
 
839
 
        self.remove_all_exercises()
840
 
        Store.of(self).remove(self)
841
 
 
842
478
class WorksheetExercise(Storm):
843
 
    """A link between a worksheet and one of its exercises.
844
 
 
845
 
    These may be marked optional, in which case the exercise does not count
846
 
    for marking purposes. The sequence number is used to order the worksheet
847
 
    ToC.
848
 
    """
849
 
 
850
 
    __storm_table__ = "worksheet_exercise"
851
 
 
852
 
    id = Int(primary=True, name="ws_ex_id")
 
479
    __storm_table__ = "worksheet_problem"
 
480
    __storm_primary__ = "worksheet_id", "exercise_id"
853
481
 
854
482
    worksheet_id = Int(name="worksheetid")
855
483
    worksheet = Reference(worksheet_id, Worksheet.id)
856
 
    exercise_id = Unicode(name="exerciseid")
 
484
    exercise_id = Unicode(name="problemid")
857
485
    exercise = Reference(exercise_id, Exercise.id)
858
486
    optional = Bool()
859
 
    active = Bool()
860
 
    seq_no = Int()
861
 
 
862
 
    saves = ReferenceSet(id, "ExerciseSave.ws_ex_id")
863
 
    attempts = ReferenceSet(id, "ExerciseAttempt.ws_ex_id")
864
487
 
865
488
    __init__ = _kwarg_init
866
489
 
867
490
    def __repr__(self):
868
491
        return "<%s %s in %s>" % (type(self).__name__, self.exercise.name,
869
 
                                  self.worksheet.identifier)
870
 
 
871
 
    def get_permissions(self, user):
872
 
        return self.worksheet.get_permissions(user)
873
 
 
 
492
                                  self.worksheet.name)
874
493
 
875
494
class ExerciseSave(Storm):
876
 
    """A potential exercise solution submitted by a user for storage.
877
 
 
878
 
    This is not an actual tested attempt at an exercise, it's just a save of
879
 
    the editing session.
880
 
    """
881
 
 
882
 
    __storm_table__ = "exercise_save"
883
 
    __storm_primary__ = "ws_ex_id", "user_id"
884
 
 
885
 
    ws_ex_id = Int(name="ws_ex_id")
886
 
    worksheet_exercise = Reference(ws_ex_id, "WorksheetExercise.id")
887
 
 
 
495
    """
 
496
    Represents a potential solution to an exercise that a user has submitted
 
497
    to the server for storage.
 
498
    A basic ExerciseSave is just the current saved text for this exercise for
 
499
    this user (doesn't count towards their attempts).
 
500
    ExerciseSave may be extended with additional semantics (such as
 
501
    ExerciseAttempt).
 
502
    """
 
503
    __storm_table__ = "problem_save"
 
504
    __storm_primary__ = "exercise_id", "user_id", "date"
 
505
 
 
506
    exercise_id = Unicode(name="problemid")
 
507
    exercise = Reference(exercise_id, Exercise.id)
888
508
    user_id = Int(name="loginid")
889
509
    user = Reference(user_id, User.id)
890
510
    date = DateTime()
891
511
    text = Unicode()
 
512
    worksheetid = Int()
 
513
    worksheet = Reference(worksheetid, Worksheet.id)
892
514
 
893
515
    __init__ = _kwarg_init
894
516
 
897
519
            self.exercise.name, self.user.login, self.date.strftime("%c"))
898
520
 
899
521
class ExerciseAttempt(ExerciseSave):
900
 
    """An attempt at solving an exercise.
901
 
 
902
 
    This is a special case of ExerciseSave, used when the user submits a
903
 
    candidate solution. Like an ExerciseSave, it constitutes exercise solution
904
 
    data.
905
 
 
906
 
    In addition, it contains information about the result of the submission:
907
 
 
908
 
     - complete - True if this submission was successful, rendering this
909
 
                  exercise complete for this user in this worksheet.
910
 
     - active   - True if this submission is "active" (usually true).
911
 
                  Submissions may be de-activated by privileged users for
912
 
                  special reasons, and then they won't count (either as a
913
 
                  penalty or success), but will still be stored.
914
 
    """
915
 
 
916
 
    __storm_table__ = "exercise_attempt"
917
 
    __storm_primary__ = "ws_ex_id", "user_id", "date"
 
522
    """
 
523
    An ExerciseAttempt is a special case of an ExerciseSave. Like an
 
524
    ExerciseSave, it constitutes exercise solution data that the user has
 
525
    submitted to the server for storage.
 
526
    In addition, it contains additional information about the submission.
 
527
    complete - True if this submission was successful, rendering this exercise
 
528
        complete for this user.
 
529
    active - True if this submission is "active" (usually true). Submissions
 
530
        may be de-activated by privileged users for special reasons, and then
 
531
        they won't count (either as a penalty or success), but will still be
 
532
        stored.
 
533
    """
 
534
    __storm_table__ = "problem_attempt"
 
535
    __storm_primary__ = "exercise_id", "user_id", "date"
918
536
 
919
537
    # The "text" field is the same but has a different name in the DB table
920
538
    # for some reason.
921
539
    text = Unicode(name="attempt")
922
540
    complete = Bool()
923
541
    active = Bool()
924
 
 
 
542
    
925
543
    def get_permissions(self, user):
926
544
        return set(['view']) if user is self.user else set()
927
 
 
 
545
  
928
546
class TestSuite(Storm):
929
 
    """A container to group an exercise's test cases.
930
 
 
931
 
    The test suite contains some information on how to test. The function to
932
 
    test, variables to set and stdin data are stored here.
933
 
    """
934
 
 
 
547
    """A Testsuite acts as a container for the test cases of an exercise."""
935
548
    __storm_table__ = "test_suite"
936
549
    __storm_primary__ = "exercise_id", "suiteid"
937
 
 
 
550
    
938
551
    suiteid = Int()
939
 
    exercise_id = Unicode(name="exerciseid")
 
552
    exercise_id = Unicode(name="problemid")
 
553
    exercise = Reference(exercise_id, Exercise.id)
 
554
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid')
940
555
    description = Unicode()
941
556
    seq_no = Int()
942
 
    function = Unicode()
943
 
    stdin = Unicode()
944
 
    exercise = Reference(exercise_id, Exercise.id)
945
 
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid', order_by="seq_no")
946
 
    variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid', order_by='arg_no')
947
 
 
948
 
    def delete(self):
949
 
        """Delete this suite, without asking questions."""
950
 
        for vaariable in self.variables:
951
 
            variable.delete()
952
 
        for test_case in self.test_cases:
953
 
            test_case.delete()
954
 
        Store.of(self).remove(self)
955
557
 
956
558
class TestCase(Storm):
957
 
    """A container for actual tests (see TestCasePart), inside a test suite.
958
 
 
959
 
    It is the lowest level shown to students on their pass/fail status."""
960
 
 
 
559
    """A TestCase is a member of a TestSuite.
 
560
    
 
561
    It contains the data necessary to check if an exercise is correct"""
961
562
    __storm_table__ = "test_case"
962
563
    __storm_primary__ = "testid", "suiteid"
963
 
 
 
564
    
964
565
    testid = Int()
965
566
    suiteid = Int()
966
 
    suite = Reference(suiteid, "TestSuite.suiteid")
 
567
    suite = Reference(suiteid, TestSuite.suiteid)
967
568
    passmsg = Unicode()
968
569
    failmsg = Unicode()
969
 
    test_default = Unicode()
 
570
    init = Unicode()
 
571
    code_type = Unicode()
 
572
    code = Unicode()
 
573
    testtype = Unicode()
970
574
    seq_no = Int()
971
 
 
972
 
    parts = ReferenceSet(testid, "TestCasePart.testid")
973
 
 
974
 
    __init__ = _kwarg_init
975
 
 
976
 
    def delete(self):
977
 
        for part in self.parts:
978
 
            part.delete()
979
 
        Store.of(self).remove(self)
980
 
 
981
 
class TestSuiteVar(Storm):
982
 
    """A variable used by an exercise test suite.
983
 
 
984
 
    This may represent a function argument or a normal variable.
985
 
    """
986
 
 
987
 
    __storm_table__ = "suite_variable"
988
 
    __storm_primary__ = "varid"
989
 
 
990
 
    varid = Int()
991
 
    suiteid = Int()
992
 
    var_name = Unicode()
993
 
    var_value = Unicode()
994
 
    var_type = Unicode()
995
 
    arg_no = Int()
996
 
 
997
 
    suite = Reference(suiteid, "TestSuite.suiteid")
998
 
 
999
 
    __init__ = _kwarg_init
1000
 
 
1001
 
    def delete(self):
1002
 
        Store.of(self).remove(self)
1003
 
 
1004
 
class TestCasePart(Storm):
1005
 
    """An actual piece of code to test an exercise solution."""
1006
 
 
1007
 
    __storm_table__ = "test_case_part"
1008
 
    __storm_primary__ = "partid"
1009
 
 
1010
 
    partid = Int()
1011
 
    testid = Int()
1012
 
 
1013
 
    part_type = Unicode()
1014
 
    test_type = Unicode()
1015
 
    data = Unicode()
1016
 
    filename = Unicode()
1017
 
 
1018
 
    test = Reference(testid, "TestCase.testid")
1019
 
 
1020
 
    __init__ = _kwarg_init
1021
 
 
1022
 
    def delete(self):
1023
 
        Store.of(self).remove(self)
 
575
    
 
576
    __init__ = _kwarg_init