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

« back to all changes in this revision

Viewing changes to ivle/database.py

Add Project.latest_submissions, which excludes superseded submissions.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
# Author: Matt Giuca, Will Grant
19
19
 
20
 
"""
21
 
Database Classes and Utilities for Storm ORM
 
20
"""Database utilities and content classes.
22
21
 
23
22
This module provides all of the classes which map to database tables.
24
23
It also provides miscellaneous utility functions for database interaction.
25
24
"""
26
25
 
27
 
import md5
 
26
import hashlib
28
27
import datetime
29
28
 
30
29
from storm.locals import create_database, Store, Int, Unicode, DateTime, \
31
30
                         Reference, ReferenceSet, Bool, Storm, Desc
 
31
from storm.expr import Select, Max
 
32
from storm.exceptions import NotOneError, IntegrityError
32
33
 
33
 
import ivle.conf
34
 
import ivle.caps
 
34
from ivle.worksheet.rst import rst
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',
40
41
            'Exercise', 'Worksheet', 'WorksheetExercise',
41
42
            'ExerciseSave', 'ExerciseAttempt',
42
 
            'AlreadyEnrolledError'
 
43
            'TestCase', 'TestSuite', 'TestSuiteVar'
43
44
        ]
44
45
 
45
46
def _kwarg_init(self, **kwargs):
49
50
                % (self.__class__.__name__, k))
50
51
        setattr(self, k, v)
51
52
 
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()))
 
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)))
66
79
 
67
80
# USERS #
68
81
 
69
82
class User(Storm):
70
 
    """
71
 
    Represents an IVLE user.
72
 
    """
 
83
    """An IVLE user account."""
73
84
    __storm_table__ = "login"
74
85
 
75
86
    id = Int(primary=True, name="loginid")
76
87
    login = Unicode()
77
88
    passhash = Unicode()
78
89
    state = Unicode()
79
 
    rolenm = Unicode()
 
90
    admin = Bool()
80
91
    unixid = Int()
81
92
    nick = Unicode()
82
93
    pass_exp = DateTime()
88
99
    studentid = Unicode()
89
100
    settings = Unicode()
90
101
 
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
 
 
101
102
    __init__ = _kwarg_init
102
103
 
103
104
    def __repr__(self):
114
115
            return None
115
116
        return self.hash_password(password) == self.passhash
116
117
 
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)
 
118
    @property
 
119
    def display_name(self):
 
120
        return self.fullname
122
121
 
123
122
    @property
124
123
    def password_expired(self):
130
129
        fieldval = self.acct_exp
131
130
        return fieldval is not None and datetime.datetime.now() > fieldval
132
131
 
 
132
    @property
 
133
    def valid(self):
 
134
        return self.state == 'enabled' and not self.account_expired
 
135
 
133
136
    def _get_enrolments(self, justactive):
134
137
        return Store.of(self).find(Enrolment,
135
138
            Enrolment.user_id == self.id,
159
162
 
160
163
    # TODO: Invitations should be listed too?
161
164
    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
        """
162
169
        preds = [
163
170
            ProjectGroupMembership.user_id == self.id,
164
171
            ProjectGroup.id == ProjectGroupMembership.project_group_id,
184
191
        '''A sanely ordered list of all of the user's enrolments.'''
185
192
        return self._get_enrolments(False) 
186
193
 
 
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
 
187
214
    @staticmethod
188
215
    def hash_password(password):
189
 
        return md5.md5(password).hexdigest()
 
216
        """Hash a password with MD5."""
 
217
        return hashlib.md5(password).hexdigest()
190
218
 
191
219
    @classmethod
192
220
    def get_by_login(cls, store, login):
193
 
        """
194
 
        Get the User from the db associated with a given store and
195
 
        login.
196
 
        """
 
221
        """Find a user in a store by login name."""
197
222
        return store.find(cls, cls.login == unicode(login)).one()
198
223
 
 
224
    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'])
 
232
        else:
 
233
            return set()
 
234
 
199
235
# SUBJECTS AND ENROLMENTS #
200
236
 
201
237
class Subject(Storm):
 
238
    """A subject (or course) which is run in some semesters."""
 
239
 
202
240
    __storm_table__ = "subject"
203
241
 
204
242
    id = Int(primary=True, name="subjectid")
214
252
    def __repr__(self):
215
253
        return "<%s '%s'>" % (type(self).__name__, self.short_name)
216
254
 
 
255
    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
        perms = set()
 
262
        if user is not None:
 
263
            perms.add('view')
 
264
            if user.admin:
 
265
                perms.add('edit')
 
266
        return perms
 
267
 
 
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
 
217
288
class Semester(Storm):
 
289
    """A semester in which subjects can be run."""
 
290
 
218
291
    __storm_table__ = "semester"
219
292
 
220
293
    id = Int(primary=True, name="semesterid")
221
294
    year = Unicode()
222
295
    semester = Unicode()
223
 
    active = Bool()
 
296
    state = Unicode()
224
297
 
225
298
    offerings = ReferenceSet(id, 'Offering.semester_id')
 
299
    enrolments = ReferenceSet(id,
 
300
                              'Offering.semester_id',
 
301
                              'Offering.id',
 
302
                              'Enrolment.offering_id')
226
303
 
227
304
    __init__ = _kwarg_init
228
305
 
230
307
        return "<%s %s/%s>" % (type(self).__name__, self.year, self.semester)
231
308
 
232
309
class Offering(Storm):
 
310
    """An offering of a subject in a particular semester."""
 
311
 
233
312
    __storm_table__ = "offering"
234
313
 
235
314
    id = Int(primary=True, name="offeringid")
246
325
                           'User.id')
247
326
    project_sets = ReferenceSet(id, 'ProjectSet.offering_id')
248
327
 
 
328
    worksheets = ReferenceSet(id, 
 
329
        'Worksheet.offering_id', 
 
330
        order_by="seq_no"
 
331
    )
 
332
 
249
333
    __init__ = _kwarg_init
250
334
 
251
335
    def __repr__(self):
252
336
        return "<%s %r in %r>" % (type(self).__name__, self.subject,
253
337
                                  self.semester)
254
338
 
255
 
    def enrol(self, user):
256
 
        '''Enrol a user in this offering.'''
257
 
        # We'll get a horrible database constraint violation error if we try
258
 
        # to add a second enrolment.
259
 
        if Store.of(self).find(Enrolment,
260
 
                               Enrolment.user_id == user.id,
261
 
                               Enrolment.offering_id == self.id).count() == 1:
262
 
            raise AlreadyEnrolledError()
263
 
 
264
 
        e = Enrolment(user=user, offering=self, active=True)
265
 
        self.enrolments.add(e)
 
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')
266
393
 
267
394
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
 
268
400
    __storm_table__ = "enrolment"
269
401
    __storm_primary__ = "user_id", "offering_id"
270
402
 
272
404
    user = Reference(user_id, User.id)
273
405
    offering_id = Int(name="offeringid")
274
406
    offering = Reference(offering_id, Offering.id)
 
407
    role = Unicode()
275
408
    notes = Unicode()
276
409
    active = Bool()
277
410
 
289
422
        return "<%s %r in %r>" % (type(self).__name__, self.user,
290
423
                                  self.offering)
291
424
 
292
 
class AlreadyEnrolledError(Exception):
293
 
    pass
294
 
 
295
425
# PROJECTS #
296
426
 
297
427
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
 
298
434
    __storm_table__ = "project_set"
299
435
 
300
436
    id = Int(name="projectsetid", primary=True)
311
447
        return "<%s %d in %r>" % (type(self).__name__, self.id,
312
448
                                  self.offering)
313
449
 
 
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
 
314
465
class Project(Storm):
 
466
    """A student project for which submissions can be made."""
 
467
 
315
468
    __storm_table__ = "project"
316
469
 
317
470
    id = Int(name="projectid", primary=True)
 
471
    name = Unicode()
 
472
    short_name = Unicode()
318
473
    synopsis = Unicode()
319
474
    url = Unicode()
320
475
    project_set_id = Int(name="projectsetid")
321
476
    project_set = Reference(project_set_id, ProjectSet.id)
322
477
    deadline = DateTime()
323
478
 
 
479
    assesseds = ReferenceSet(id, 'Assessed.project_id')
 
480
    submissions = ReferenceSet(id,
 
481
                               'Assessed.project_id',
 
482
                               'Assessed.id',
 
483
                               'ProjectSubmission.assessed_id')
 
484
 
324
485
    __init__ = _kwarg_init
325
486
 
326
487
    def __repr__(self):
327
 
        return "<%s '%s' in %r>" % (type(self).__name__, self.synopsis,
 
488
        return "<%s '%s' in %r>" % (type(self).__name__, self.short_name,
328
489
                                  self.project_set.offering)
329
490
 
 
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
 
330
535
class ProjectGroup(Storm):
 
536
    """A group of students working together on a project."""
 
537
 
331
538
    __storm_table__ = "project_group"
332
539
 
333
540
    id = Int(name="groupid", primary=True)
350
557
        return "<%s %s in %r>" % (type(self).__name__, self.name,
351
558
                                  self.project_set.offering)
352
559
 
 
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
 
353
590
class ProjectGroupMembership(Storm):
 
591
    """A student's membership in a project group."""
 
592
 
354
593
    __storm_table__ = "group_member"
355
594
    __storm_primary__ = "user_id", "project_group_id"
356
595
 
365
604
        return "<%s %r in %r>" % (type(self).__name__, self.user,
366
605
                                  self.project_group)
367
606
 
 
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 principal(self):
 
634
        return self.project_group or self.user
 
635
 
 
636
    @classmethod
 
637
    def get(cls, store, principal, project):
 
638
        """Find or create an Assessed for the given user or group and project.
 
639
 
 
640
        @param principal: The user or group.
 
641
        @param project: The project.
 
642
        """
 
643
        t = type(principal)
 
644
        if t not in (User, ProjectGroup):
 
645
            raise AssertionError('principal must be User or ProjectGroup')
 
646
 
 
647
        a = store.find(cls,
 
648
            (t is User) or (cls.project_group_id == principal.id),
 
649
            (t is ProjectGroup) or (cls.user_id == principal.id),
 
650
            Project.id == project.id).one()
 
651
 
 
652
        if a is None:
 
653
            a = cls()
 
654
            if t is User:
 
655
                a.user = principal
 
656
            else:
 
657
                a.project_group = principal
 
658
            a.project = project
 
659
            store.add(a)
 
660
 
 
661
        return a
 
662
 
 
663
 
 
664
class ProjectExtension(Storm):
 
665
    """An extension granted to a user or group on a particular project.
 
666
 
 
667
    The user or group and project are specified by the Assessed.
 
668
    """
 
669
 
 
670
    __storm_table__ = "project_extension"
 
671
 
 
672
    id = Int(name="extensionid", primary=True)
 
673
    assessed_id = Int(name="assessedid")
 
674
    assessed = Reference(assessed_id, Assessed.id)
 
675
    deadline = DateTime()
 
676
    approver_id = Int(name="approver")
 
677
    approver = Reference(approver_id, User.id)
 
678
    notes = Unicode()
 
679
 
 
680
class ProjectSubmission(Storm):
 
681
    """A submission from a user or group repository to a particular project.
 
682
 
 
683
    The content of a submission is a single path and revision inside a
 
684
    repository. The repository is that owned by the submission's user and
 
685
    group, while the path and revision are explicit.
 
686
 
 
687
    The user or group and project are specified by the Assessed.
 
688
    """
 
689
 
 
690
    __storm_table__ = "project_submission"
 
691
 
 
692
    id = Int(name="submissionid", primary=True)
 
693
    assessed_id = Int(name="assessedid")
 
694
    assessed = Reference(assessed_id, Assessed.id)
 
695
    path = Unicode()
 
696
    revision = Int()
 
697
    submitter_id = Int(name="submitter")
 
698
    submitter = Reference(submitter_id, User.id)
 
699
    date_submitted = DateTime()
 
700
 
 
701
 
368
702
# WORKSHEETS AND EXERCISES #
369
703
 
370
704
class Exercise(Storm):
371
 
    # Note: Table "problem" is called "Exercise" in the Object layer, since
372
 
    # it's called that everywhere else.
373
 
    __storm_table__ = "problem"
374
 
 
375
 
    id = Int(primary=True, name="problemid")
376
 
    name = Unicode(name="identifier")
377
 
    spec = Unicode()
 
705
    """An exercise for students to complete in a worksheet.
 
706
 
 
707
    An exercise may be present in any number of worksheets.
 
708
    """
 
709
 
 
710
    __storm_table__ = "exercise"
 
711
    id = Unicode(primary=True, name="identifier")
 
712
    name = Unicode()
 
713
    description = Unicode()
 
714
    partial = Unicode()
 
715
    solution = Unicode()
 
716
    include = Unicode()
 
717
    num_rows = Int()
 
718
 
 
719
    worksheet_exercises =  ReferenceSet(id,
 
720
        'WorksheetExercise.exercise_id')
378
721
 
379
722
    worksheets = ReferenceSet(id,
380
723
        'WorksheetExercise.exercise_id',
382
725
        'Worksheet.id'
383
726
    )
384
727
 
 
728
    test_suites = ReferenceSet(id, 
 
729
        'TestSuite.exercise_id',
 
730
        order_by='seq_no')
 
731
 
385
732
    __init__ = _kwarg_init
386
733
 
387
734
    def __repr__(self):
388
735
        return "<%s %s>" % (type(self).__name__, self.name)
389
736
 
390
 
    @classmethod
391
 
    def get_by_name(cls, store, name):
392
 
        """
393
 
        Get the Exercise from the db associated with a given store and name.
394
 
        If the exercise is not in the database, creates it and inserts it
395
 
        automatically.
396
 
        """
397
 
        ex = store.find(cls, cls.name == unicode(name)).one()
398
 
        if ex is not None:
399
 
            return ex
400
 
        ex = Exercise(name=unicode(name))
401
 
        store.add(ex)
402
 
        store.commit()
403
 
        return ex
 
737
    def get_permissions(self, user):
 
738
        perms = set()
 
739
        roles = set()
 
740
        if user is not None:
 
741
            if user.admin:
 
742
                perms.add('edit')
 
743
                perms.add('view')
 
744
            elif u'lecturer' in set((e.role for e in user.active_enrolments)):
 
745
                perms.add('edit')
 
746
                perms.add('view')
 
747
            elif u'tutor' in set((e.role for e in user.active_enrolments)):
 
748
                perms.add('edit')
 
749
                perms.add('view')
 
750
 
 
751
        return perms
 
752
 
 
753
    def get_description(self):
 
754
        """Return the description interpreted as reStructuredText."""
 
755
        return rst(self.description)
 
756
 
 
757
    def delete(self):
 
758
        """Deletes the exercise, providing it has no associated worksheets."""
 
759
        if (self.worksheet_exercises.count() > 0):
 
760
            raise IntegrityError()
 
761
        for suite in self.test_suites:
 
762
            suite.delete()
 
763
        Store.of(self).remove(self)
404
764
 
405
765
class Worksheet(Storm):
 
766
    """A worksheet with exercises for students to complete.
 
767
 
 
768
    Worksheets are owned by offerings.
 
769
    """
 
770
 
406
771
    __storm_table__ = "worksheet"
407
772
 
408
773
    id = Int(primary=True, name="worksheetid")
409
 
    # XXX subject is not linked to a Subject object. This is a property of
410
 
    # the database, and will be refactored.
411
 
    subject = Unicode()
412
 
    name = Unicode(name="identifier")
 
774
    offering_id = Int(name="offeringid")
 
775
    identifier = Unicode()
 
776
    name = Unicode()
413
777
    assessable = Bool()
414
 
    mtime = DateTime()
415
 
 
416
 
    exercises = ReferenceSet(id,
417
 
        'WorksheetExercise.worksheet_id',
418
 
        'WorksheetExercise.exercise_id',
419
 
        Exercise.id)
420
 
    # Use worksheet_exercises to get access to the WorksheetExercise objects
421
 
    # binding worksheets to exercises. This is required to access the
 
778
    data = Unicode()
 
779
    seq_no = Int()
 
780
    format = Unicode()
 
781
 
 
782
    attempts = ReferenceSet(id, "ExerciseAttempt.worksheetid")
 
783
    offering = Reference(offering_id, 'Offering.id')
 
784
 
 
785
    all_worksheet_exercises = ReferenceSet(id,
 
786
        'WorksheetExercise.worksheet_id')
 
787
 
 
788
    # Use worksheet_exercises to get access to the *active* WorksheetExercise
 
789
    # objects binding worksheets to exercises. This is required to access the
422
790
    # "optional" field.
423
 
    worksheet_exercises = ReferenceSet(id,
424
 
        'WorksheetExercise.worksheet_id')
 
791
 
 
792
    @property
 
793
    def worksheet_exercises(self):
 
794
        return self.all_worksheet_exercises.find(active=True)
425
795
 
426
796
    __init__ = _kwarg_init
427
797
 
428
798
    def __repr__(self):
429
799
        return "<%s %s>" % (type(self).__name__, self.name)
430
800
 
431
 
    # XXX Refactor this - make it an instance method of Subject rather than a
432
 
    # class method of Worksheet. Can't do that now because Subject isn't
433
 
    # linked referentially to the Worksheet.
434
 
    @classmethod
435
 
    def get_by_name(cls, store, subjectname, worksheetname):
436
 
        """
437
 
        Get the Worksheet from the db associated with a given store, subject
438
 
        name and worksheet name.
439
 
        """
440
 
        return store.find(cls, cls.subject == unicode(subjectname),
441
 
            cls.name == unicode(worksheetname)).one()
 
801
    def remove_all_exercises(self):
 
802
        """Remove all exercises from this worksheet.
442
803
 
443
 
    def remove_all_exercises(self, store):
444
 
        """
445
 
        Remove all exercises from this worksheet.
446
804
        This does not delete the exercises themselves. It just removes them
447
805
        from the worksheet.
448
806
        """
 
807
        store = Store.of(self)
 
808
        for ws_ex in self.all_worksheet_exercises:
 
809
            if ws_ex.saves.count() > 0 or ws_ex.attempts.count() > 0:
 
810
                raise IntegrityError()
449
811
        store.find(WorksheetExercise,
450
812
            WorksheetExercise.worksheet == self).remove()
451
813
 
 
814
    def get_permissions(self, user):
 
815
        return self.offering.get_permissions(user)
 
816
 
 
817
    def get_xml(self):
 
818
        """Returns the xml of this worksheet, converts from rst if required."""
 
819
        if self.format == u'rst':
 
820
            ws_xml = rst(self.data)
 
821
            return ws_xml
 
822
        else:
 
823
            return self.data
 
824
 
 
825
    def delete(self):
 
826
        """Deletes the worksheet, provided it has no attempts on any exercises.
 
827
 
 
828
        Returns True if delete succeeded, or False if this worksheet has
 
829
        attempts attached."""
 
830
        for ws_ex in self.all_worksheet_exercises:
 
831
            if ws_ex.saves.count() > 0 or ws_ex.attempts.count() > 0:
 
832
                raise IntegrityError()
 
833
 
 
834
        self.remove_all_exercises()
 
835
        Store.of(self).remove(self)
 
836
 
452
837
class WorksheetExercise(Storm):
453
 
    __storm_table__ = "worksheet_problem"
454
 
    __storm_primary__ = "worksheet_id", "exercise_id"
 
838
    """A link between a worksheet and one of its exercises.
 
839
 
 
840
    These may be marked optional, in which case the exercise does not count
 
841
    for marking purposes. The sequence number is used to order the worksheet
 
842
    ToC.
 
843
    """
 
844
 
 
845
    __storm_table__ = "worksheet_exercise"
 
846
 
 
847
    id = Int(primary=True, name="ws_ex_id")
455
848
 
456
849
    worksheet_id = Int(name="worksheetid")
457
850
    worksheet = Reference(worksheet_id, Worksheet.id)
458
 
    exercise_id = Int(name="problemid")
 
851
    exercise_id = Unicode(name="exerciseid")
459
852
    exercise = Reference(exercise_id, Exercise.id)
460
853
    optional = Bool()
 
854
    active = Bool()
 
855
    seq_no = Int()
 
856
 
 
857
    saves = ReferenceSet(id, "ExerciseSave.ws_ex_id")
 
858
    attempts = ReferenceSet(id, "ExerciseAttempt.ws_ex_id")
461
859
 
462
860
    __init__ = _kwarg_init
463
861
 
464
862
    def __repr__(self):
465
863
        return "<%s %s in %s>" % (type(self).__name__, self.exercise.name,
466
 
                                  self.worksheet.name)
 
864
                                  self.worksheet.identifier)
 
865
 
 
866
    def get_permissions(self, user):
 
867
        return self.worksheet.get_permissions(user)
 
868
 
467
869
 
468
870
class ExerciseSave(Storm):
469
 
    """
470
 
    Represents a potential solution to an exercise that a user has submitted
471
 
    to the server for storage.
472
 
    A basic ExerciseSave is just the current saved text for this exercise for
473
 
    this user (doesn't count towards their attempts).
474
 
    ExerciseSave may be extended with additional semantics (such as
475
 
    ExerciseAttempt).
476
 
    """
477
 
    __storm_table__ = "problem_save"
478
 
    __storm_primary__ = "exercise_id", "user_id", "date"
479
 
 
480
 
    exercise_id = Int(name="problemid")
481
 
    exercise = Reference(exercise_id, Exercise.id)
 
871
    """A potential exercise solution submitted by a user for storage.
 
872
 
 
873
    This is not an actual tested attempt at an exercise, it's just a save of
 
874
    the editing session.
 
875
    """
 
876
 
 
877
    __storm_table__ = "exercise_save"
 
878
    __storm_primary__ = "ws_ex_id", "user_id"
 
879
 
 
880
    ws_ex_id = Int(name="ws_ex_id")
 
881
    worksheet_exercise = Reference(ws_ex_id, "WorksheetExercise.id")
 
882
 
482
883
    user_id = Int(name="loginid")
483
884
    user = Reference(user_id, User.id)
484
885
    date = DateTime()
491
892
            self.exercise.name, self.user.login, self.date.strftime("%c"))
492
893
 
493
894
class ExerciseAttempt(ExerciseSave):
494
 
    """
495
 
    An ExerciseAttempt is a special case of an ExerciseSave. Like an
496
 
    ExerciseSave, it constitutes exercise solution data that the user has
497
 
    submitted to the server for storage.
498
 
    In addition, it contains additional information about the submission.
499
 
    complete - True if this submission was successful, rendering this exercise
500
 
        complete for this user.
501
 
    active - True if this submission is "active" (usually true). Submissions
502
 
        may be de-activated by privileged users for special reasons, and then
503
 
        they won't count (either as a penalty or success), but will still be
504
 
        stored.
505
 
    """
506
 
    __storm_table__ = "problem_attempt"
507
 
    __storm_primary__ = "exercise_id", "user_id", "date"
 
895
    """An attempt at solving an exercise.
 
896
 
 
897
    This is a special case of ExerciseSave, used when the user submits a
 
898
    candidate solution. Like an ExerciseSave, it constitutes exercise solution
 
899
    data.
 
900
 
 
901
    In addition, it contains information about the result of the submission:
 
902
 
 
903
     - complete - True if this submission was successful, rendering this
 
904
                  exercise complete for this user in this worksheet.
 
905
     - active   - True if this submission is "active" (usually true).
 
906
                  Submissions may be de-activated by privileged users for
 
907
                  special reasons, and then they won't count (either as a
 
908
                  penalty or success), but will still be stored.
 
909
    """
 
910
 
 
911
    __storm_table__ = "exercise_attempt"
 
912
    __storm_primary__ = "ws_ex_id", "user_id", "date"
508
913
 
509
914
    # The "text" field is the same but has a different name in the DB table
510
915
    # for some reason.
511
916
    text = Unicode(name="attempt")
512
917
    complete = Bool()
513
918
    active = Bool()
 
919
 
 
920
    def get_permissions(self, user):
 
921
        return set(['view']) if user is self.user else set()
 
922
 
 
923
class TestSuite(Storm):
 
924
    """A container to group an exercise's test cases.
 
925
 
 
926
    The test suite contains some information on how to test. The function to
 
927
    test, variables to set and stdin data are stored here.
 
928
    """
 
929
 
 
930
    __storm_table__ = "test_suite"
 
931
    __storm_primary__ = "exercise_id", "suiteid"
 
932
 
 
933
    suiteid = Int()
 
934
    exercise_id = Unicode(name="exerciseid")
 
935
    description = Unicode()
 
936
    seq_no = Int()
 
937
    function = Unicode()
 
938
    stdin = Unicode()
 
939
    exercise = Reference(exercise_id, Exercise.id)
 
940
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid', order_by="seq_no")
 
941
    variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid', order_by='arg_no')
 
942
 
 
943
    def delete(self):
 
944
        """Delete this suite, without asking questions."""
 
945
        for vaariable in self.variables:
 
946
            variable.delete()
 
947
        for test_case in self.test_cases:
 
948
            test_case.delete()
 
949
        Store.of(self).remove(self)
 
950
 
 
951
class TestCase(Storm):
 
952
    """A container for actual tests (see TestCasePart), inside a test suite.
 
953
 
 
954
    It is the lowest level shown to students on their pass/fail status."""
 
955
 
 
956
    __storm_table__ = "test_case"
 
957
    __storm_primary__ = "testid", "suiteid"
 
958
 
 
959
    testid = Int()
 
960
    suiteid = Int()
 
961
    suite = Reference(suiteid, "TestSuite.suiteid")
 
962
    passmsg = Unicode()
 
963
    failmsg = Unicode()
 
964
    test_default = Unicode()
 
965
    seq_no = Int()
 
966
 
 
967
    parts = ReferenceSet(testid, "TestCasePart.testid")
 
968
 
 
969
    __init__ = _kwarg_init
 
970
 
 
971
    def delete(self):
 
972
        for part in self.parts:
 
973
            part.delete()
 
974
        Store.of(self).remove(self)
 
975
 
 
976
class TestSuiteVar(Storm):
 
977
    """A variable used by an exercise test suite.
 
978
 
 
979
    This may represent a function argument or a normal variable.
 
980
    """
 
981
 
 
982
    __storm_table__ = "suite_variable"
 
983
    __storm_primary__ = "varid"
 
984
 
 
985
    varid = Int()
 
986
    suiteid = Int()
 
987
    var_name = Unicode()
 
988
    var_value = Unicode()
 
989
    var_type = Unicode()
 
990
    arg_no = Int()
 
991
 
 
992
    suite = Reference(suiteid, "TestSuite.suiteid")
 
993
 
 
994
    __init__ = _kwarg_init
 
995
 
 
996
    def delete(self):
 
997
        Store.of(self).remove(self)
 
998
 
 
999
class TestCasePart(Storm):
 
1000
    """An actual piece of code to test an exercise solution."""
 
1001
 
 
1002
    __storm_table__ = "test_case_part"
 
1003
    __storm_primary__ = "partid"
 
1004
 
 
1005
    partid = Int()
 
1006
    testid = Int()
 
1007
 
 
1008
    part_type = Unicode()
 
1009
    test_type = Unicode()
 
1010
    data = Unicode()
 
1011
    filename = Unicode()
 
1012
 
 
1013
    test = Reference(testid, "TestCase.testid")
 
1014
 
 
1015
    __init__ = _kwarg_init
 
1016
 
 
1017
    def delete(self):
 
1018
        Store.of(self).remove(self)