示例#1
0
文件: tests.py 项目: csvenja/coursys
 def setUp(self):
     p1 = Person(emplid=210012345,
                 userid="test1",
                 last_name="Lname",
                 first_name="Fname",
                 pref_first_name="Fn",
                 middle_name="M")
     p1.save()
示例#2
0
文件: tests.py 项目: avacariu/coursys
    def test_course_offering(self):
        """
        Create and test a course offering
        """
        s, c = create_offering()
        
        # should have a get_absolute_url
        url = c.get_absolute_url()
        self.assertEquals(url, str(url))
        self.assertEquals(url[0], '/')
        self.assertEquals(str(c), "CMPT 120 D100 (Fall 2007)")
        self.assertEquals(c.name(), "CMPT 120 D1")

        # check uniqueness criteria
        c2 = CourseOffering(subject="CMPT", number="120", section="D100", semester=s, component="LAB",
                graded=True, crse_id=11112, class_nbr=22223, campus='SURRY',
                enrl_cap=101, enrl_tot=100, wait_tot=3)
        # south doesn't seem to create the constraints in SQLite for testing
        #self.assertRaises(IntegrityError, c2.save)

        c2 = CourseOffering(subject="CMPT", number="121", section="D100", semester=s, component="LAB",
                graded=True, crse_id=11111, class_nbr=22223, campus='SURRY',
                enrl_cap=101, enrl_tot=100, wait_tot=3)
        # south doesn't seem to create the constraints in SQLite for testing
        #self.assertRaises(IntegrityError, c2.save)

        c2 = CourseOffering(subject="MACM", number="121", section="D102", semester=s, component="LAB",
                graded=True, crse_id=11112, class_nbr=22222, campus='SURRY',
                enrl_cap=101, enrl_tot=100, wait_tot=3)
        # south doesn't seem to create the constraints in SQLite for testing
        #self.assertRaises(IntegrityError, c2.save)

        # test some course memberships
        p1 = Person(emplid=210012345, userid="test1",
                last_name="Lname", first_name="Fname", pref_first_name="Fn", middle_name="M")
        p1.save()
        m = Member(person=p1, offering=c, role="INST", credits=0, career="NONS", added_reason="AUTO")
        m.save()
        
        self.assertEqual( str(list(c.instructors())), "[<Person: Lname, Fname>]")
        self.assertEqual( str(list(c.tas())), "[]")
        self.assertEqual( c.student_count(), 0)

        m.role = "TA"
        m.save()
        self.assertEqual( str(list(c.instructors())), "[]")
        self.assertEqual( str(list(c.tas())), "[<Person: Lname, Fname>]")
        self.assertEqual( c.student_count(), 0)

        m.role = "STUD"
        m.save()
        self.assertEqual( str(list(c.instructors())), "[]")
        self.assertEqual( str(list(c.tas())), "[]")
        self.assertEqual( c.student_count(), 1)
        
        self.assertEqual( str(m), "test1 (210012345) in CMPT 120 D100 (Fall 2007)")
示例#3
0
文件: tests.py 项目: csvenja/coursys
 def test_person_2(self):
     p1 = Person(emplid=210012345,
                 userid="test1",
                 last_name="Lname",
                 first_name="Fname",
                 pref_first_name="Fn",
                 middle_name="M")
     p1.save()
     px = Person(emplid=210012348, userid="test1")
     self.assertRaises(IntegrityError, px.save)
示例#4
0
    def test_roles(self):
        # create person an give sysadmin role
        p1 = Person(emplid=210012345,
                    userid="test1",
                    last_name="Lname",
                    first_name="Fname",
                    pref_first_name="Fn",
                    middle_name="M")
        p1.save()

        unit = Unit.objects.get(label="UNIV")
        r = Role(person=p1, role="SYSA", unit=unit, expiry=TEST_ROLE_EXPIRY)
        r.save()
        self.assertEqual(str(r), "Lname, Fname (System Administrator, UNIV)")

        # check the front end
        client = Client()
        client.login_user("test1")

        url = reverse('sysadmin:role_list')
        response = basic_page_tests(self, client, url)
        self.assertContains(
            response, 'Lname, Fname</a></td>\n  <td>System Administrator</td>')

        # add a new role with the front end
        oldcount = Role.objects.filter(role='FAC').count()
        url = reverse('sysadmin:new_role')
        response = basic_page_tests(self, client, url)

        response = client.post(url, {
            'person': '33333333',
            'role': 'FAC',
            'unit': 2
        })
        self.assertEqual(response.status_code, 200)
        validate_content(self, response.content, url)
        self.assertTrue(
            b"could not import DB2 module" in response.content
            or b"could not connect to reporting database" in response.content
            or b"Could not find this emplid." in response.content or
            b"Reporting database access has been disabled" in response.content
            or b"Could not communicate with reporting database"
            in response.content)

        response = client.post(
            url, {
                'person': p1.emplid,
                'role': 'FAC',
                'unit': unit.id,
                'expiry': str(TEST_ROLE_EXPIRY)
            })
        self.assertEqual(response.status_code, 302)

        # make sure the role is now there
        self.assertEqual(Role.objects.filter(role='FAC').count(), oldcount + 1)
示例#5
0
def new_temporary_person(request):
    if request.method == 'POST':
        form = TemporaryPersonForm(request.POST)
        if form.is_valid():
            p = Person(first_name=form.cleaned_data['first_name'],
                       last_name=form.cleaned_data['last_name'],
                       emplid=Person.next_available_temp_emplid(),
                       userid=Person.next_available_temp_userid(),
                       temporary=True)
            if form.cleaned_data['email']:
                p.config['email'] = form.cleaned_data['email']
            if form.cleaned_data['sin']:
                p.config['sin'] = form.cleaned_data['sin']

            p.save()

            messages.success(request, 'Added new temporary person %s' % (p, ))
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                         description=("new temporary person: %s") % (p, ),
                         related_object=p)
            l.save()
            return HttpResponseRedirect(reverse(unit_admin))
    else:
        form = TemporaryPersonForm()

    return render(request, 'coredata/new_temporary_person.html',
                  {'form': form})
示例#6
0
def fakedata_import():
    print("creating other data")
    create_others()
    create_grads()
    create_grad_templ()
    create_more_data()
    create_form_data()
    create_ta_data()
    create_ra_data()

    print("giving sysadmin permissions")
    p=Person(userid='sysa', first_name='System', last_name='Admin', emplid='000054312')
    p.save()
    Role.objects.get_or_create(person=p, role='SYSA', unit=Unit.objects.get(slug='univ'))
示例#7
0
def fakedata_import():
    print "creating other data"
    create_others()
    create_grads()
    create_grad_templ()
    create_more_data()
    create_form_data()
    create_ta_data()
    create_ra_data()

    print "giving sysadmin permissions"
    p=Person(userid='sysa', first_name='System', last_name='Admin', emplid='000054312')
    p.save()
    Role.objects.get_or_create(person=p, role='SYSA', unit=Unit.objects.get(slug='univ'))
示例#8
0
def create_fake_gradstudents():
    """
    Make a bunch of fake grad students so we can test searching
    """
    for i in range(100):
        userid = "1grad%s" % (i)
        fname = randname(8)
        lname = "Gradstudent"
        p = Person(emplid=fake_emplid(userid), userid=userid, last_name=lname, first_name=fname, middle_name="", pref_first_name=fname[:4])
        p.config['gender'] = random.choice(('M','F','U'))
        p.config['gpa'] = random.triangular(0.0, 4.33, 2.33)
        p.config['visa'] = random.choice([x for x,_ in forms.VISA_STATUSES])
        p.config['citizen'] = random.choice(('Canadian', 'OtherCountrian'))
        p.save()
        all_students[userid] = p
        
        g = GradStudent(
                person=p,
                program=random.choice(GradProgram.objects.all()),
                research_area=randname(8)+'ology',
                campus=random.choice([x for x,_ in models.CAMPUS_CHOICES]),
                is_canadian=randnullbool(),
                application_status=random.choice([x for x,_ in models.APPLICATION_STATUS_CHOICES]))
        g.save()
        all_gradstudents[userid] = g
示例#9
0
文件: testing.py 项目: tjkind/coursys
def create_test_offering():
    """
    Create a CourseOffering (and related stuff) that can be used in tests with no fixtures
    """
    s = create_fake_semester('1144')
    u = Unit(label='BABL', name="Department of Babbling")
    u.save()
    o = CourseOffering(subject='BABL',
                       number='123',
                       section='F104',
                       semester=s,
                       component='LEC',
                       owner=u,
                       title='Babbling for Baferad Ferzizzles',
                       enrl_cap=100,
                       enrl_tot=5,
                       wait_tot=0)
    o.save()

    i = Person(first_name='Insley',
               last_name='Instructorberg',
               emplid=20000009,
               userid='instr')
    i.save()
    s = Person(first_name='Stanley',
               last_name='Studentson',
               emplid=20000010,
               userid='student')
    s.save()

    Member(offering=o, person=i, role='INST').save()
    Member(offering=o, person=s, role='STUD').save()

    return o
示例#10
0
    def handle(self, *args, **options):
        assert settings.DEPLOY_MODE != 'production'
        raise NotImplementedError()

        n_fake = 200
        fake_students = [Person(
            emplid=str(500000000 + i),
            userid='fake%03i' % (i,),
            last_name='Fake',
            first_name=random_name(8),
            middle_name=random_name(5),
            title=random.choice(['Mr', 'M', 'Ms', 'Dr', 'Count'])
        ) for i in range(n_fake)]
        for p in fake_students:
            p.pref_first_name = random.choice([None, p.first_name[:4]])

        students_per_class = 10
        for o in CourseOffering.objects.all():
            student_people = random.choices(fake_students, k=students_per_class)
            student_members = [
                Member(person=p, offering=o, role='STUD', added_reason='AUTO', credits=3, career='UGRD')
                for p in student_people
            ]
            data.append(student_members)


        print(serializers.serialize('json', itertools.chain(*data), indent=2))
示例#11
0
def main():
    for strm in NEEDED_SEMESTERS:
        create_fake_semester(strm)
    Unit.objects.get_or_create(label='UNIV', name='Simon Fraser University')

    print "importing course offerings"
    offerings = import_offerings(
        import_semesters=import_semesters, create_units=True
    )  # extra_where="ct.subject='CMPT' or ct.subject='ENSC'"
    offerings = list(offerings)
    offerings.sort()

    print "importing course members"
    for o in offerings:
        import_offering_members(o, students=False)

    # should now have all the "real" people: fake their emplids
    fake_emplids()

    print "creating fake classess"
    create_classes()
    create_others()
    create_grads()
    create_grad_templ()
    create_more_data()
    create_form_data()
    create_ta_data()
    create_ra_data()

    print "giving sysadmin permissions"
    Person(userid='sysa',
           first_name='System',
           last_name='Admin',
           emplid='000054312').save()
    give_sysadmin(['sysa'])
示例#12
0
    def setUp(self):
        p1 = Person(emplid=210012345,
                    userid="test1",
                    last_name="Lname",
                    first_name="Fname",
                    pref_first_name="Fn",
                    middle_name="M")
        p1.save()

        s = Semester(name="1077",
                     start=date(2007, 9, 4),
                     end=date(2007, 12, 3))
        s.save()

        unit = Unit.objects.get(label="CMPT")
        self.co1 = CourseOffering(owner=unit,
                                  subject="CMPT",
                                  number="120",
                                  section="D100",
                                  semester=s,
                                  component="LEC",
                                  graded=True,
                                  crse_id=11111,
                                  class_nbr=22222,
                                  campus='BRNBY',
                                  title="Computer Stuff",
                                  enrl_cap=100,
                                  enrl_tot=99,
                                  wait_tot=2)

        self.co2 = CourseOffering(owner=unit,
                                  subject="CMPT",
                                  number="165",
                                  section="D100",
                                  semester=s,
                                  component="LEC",
                                  graded=True,
                                  crse_id=22222,
                                  class_nbr=11111,
                                  campus='SURRY',
                                  title="Web Stuff",
                                  enrl_cap=85,
                                  enrl_tot=80,
                                  wait_tot=4)
        self.co1.save()
        self.co2.save()
示例#13
0
文件: views.py 项目: avacariu/coursys
def new_temporary_person(request):
    if request.method == 'POST':
        form = TemporaryPersonForm(request.POST)
        if form.is_valid():
            p = Person( first_name = form.cleaned_data['first_name'], 
                        last_name = form.cleaned_data['last_name'],
                        emplid = Person.next_available_temp_emplid(),
                        userid = Person.next_available_temp_userid(), 
                        temporary = True)
            if form.cleaned_data['email']:
                p.config['email'] = form.cleaned_data['email']
            if form.cleaned_data['sin']:
                p.config['sin'] = form.cleaned_data['sin']

            p.save()

            messages.success(request, 'Added new temporary person %s' % (p,))
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("new temporary person: %s") % (p,),
                  related_object=p)
            l.save()
            return HttpResponseRedirect(reverse(unit_admin))
    else:
        form = TemporaryPersonForm()

    return render(request, 'coredata/new_temporary_person.html', {'form': form})
示例#14
0
文件: tests.py 项目: avacariu/coursys
 def setUp(self):
     p1 = Person(emplid=210012345, userid="test1",
             last_name="Lname", first_name="Fname", pref_first_name="Fn", middle_name="M")
     p1.save()
     
     s = Semester(name="1077", start=date(2007,9,4), end=date(2007,12,3))
     s.save()
 
     unit = Unit.objects.get(label="CMPT")
     self.co1 = CourseOffering(owner=unit, subject="CMPT", number="120", section="D100", semester=s, component="LEC",
                         graded=True, crse_id=11111, class_nbr=22222, campus='BRNBY', title="Computer Stuff",
                         enrl_cap=100, enrl_tot=99, wait_tot=2)
     
     self.co2 = CourseOffering(owner=unit, subject="CMPT", number="165", section="D100", semester=s, component="LEC",
                         graded=True, crse_id=22222, class_nbr=11111, campus='SURRY', title="Web Stuff",
                         enrl_cap=85, enrl_tot=80, wait_tot=4)
     self.co1.save()
     self.co2.save()
示例#15
0
def add_person(emplid, commit=True, get_userid=True):
    """
    Add a Person object based on the found SIMS data
    """
    with django.db.transaction.atomic():
        ps = Person.objects.filter(emplid=emplid)
        if ps:
            # person already there: ignore
            return ps[0]

        data = find_person(emplid, get_userid=get_userid)
        if not data:
            return

        p = Person(emplid=data['emplid'], last_name=data['last_name'], first_name=data['first_name'],
                   pref_first_name=data['first_name'], middle_name=data['middle_name'], userid=data['userid'])
        p.save()
    return p
示例#16
0
def create_fake_students():
    """
    Make a bunch of fake students so we can add them to classes later.
    """
    global all_students
    for lett in string.ascii_lowercase:
        for i in range(11):
            if i==10:
                userid = "0%sgrad" % (lett*3)
                fname = randname(8)
                lname = "Grad"
            else:
                userid = "0%s%i" % (lett*3, i)
                fname = randname(8)
                lname = "Student"
            p = Person(emplid=fake_emplid(), userid=userid, last_name=lname, first_name=fname, middle_name="", pref_first_name=fname[:4])
            p.save()
            all_students[userid] = p
示例#17
0
def create_fake_students():
    """
    Make a bunch of fake students so we can add them to classes later.
    """
    global all_students
    for lett in string.ascii_lowercase:
        for i in range(11):
            if i==10:
                userid = "0%sgrad" % (lett*3)
                fname = randname(8)
                lname = "Grad"
            else:
                userid = "0%s%i" % (lett*3, i)
                fname = randname(8)
                lname = "Student"
            p = Person(emplid=fake_emplid(), userid=userid, last_name=lname, first_name=fname, middle_name="", pref_first_name=fname[:4])
            p.save()
            all_students[userid] = p
示例#18
0
    def test_search_updates(self):
        """
        Make sure indexing in Haystack is working as we expect.
        """
        fname = 'TestStudentUnusualName'
        s, c = create_offering()

        # clear the search index and query: we shouldn't find anything.
        haystack_clear_index()
        results = SearchQuerySet().models(Member).filter(text__fuzzy=fname)
        self.assertEqual(results.count(), 0)

        # add something searchable and query: we don't expect it to appear in real-time
        p = Person(last_name='Test',
                   first_name=fname,
                   userid='0aaa99999',
                   emplid=123456)
        p.save()
        m = Member(person=p, offering=c, role='STUD')
        m.save()

        results = SearchQuerySet().models(Member).filter(text__fuzzy=fname)
        self.assertEqual(results.count(), 0)

        # ... but after update_index.we do.
        haystack_update_index()
        results = SearchQuerySet().models(Member).filter(text__fuzzy=fname)
        self.assertEqual(results.count(), 1)

        # same for removing from the index.
        m.role = 'DROP'
        m.save()
        results = SearchQuerySet().models(Member).filter(text__fuzzy=fname)
        self.assertEqual(results.count(), 1)

        # update_index doesn't detect a data change that excludes the object from the index_queryset
        haystack_update_index()
        results = SearchQuerySet().models(Member).filter(text__fuzzy=fname)
        self.assertEqual(results.count(), 1)

        # but rebuild_index will fix that up.
        haystack_rebuild_index()
        results = SearchQuerySet().models(Member).filter(text__fuzzy=fname)
        self.assertEqual(results.count(), 0)
示例#19
0
def create_others():
    """
    Create other users for the test data set
    """
    p = Person(emplid=fake_emplid(),
               first_name="Susan",
               last_name="Kindersley",
               pref_first_name="sumo",
               userid="sumo")
    p.save()
    r = Role(person=p, role="GRAD", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    p = Person(emplid=fake_emplid(),
               first_name="Danyu",
               last_name="Zhao",
               pref_first_name="Danyu",
               userid="dzhao")
    p.save()
    set_privacy_signed(p)
    r = Role(person=p, role="ADVS", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='dixon'),
             role="PLAN",
             unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='ggbaker'),
             role="FAC",
             unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='dixon'),
             role="FAC",
             unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='diana'),
             role="FAC",
             unit=Unit.objects.get(slug='cmpt'))
    r.save()

    p = Person.objects.get(userid='ggbaker')
    set_privacy_signed(p)
    r = Role(person=p, role="GRAD", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=p, role="ADMN", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=p, role="TAAD", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=p, role="FUND", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='popowich'),
             role="GRPD",
             unit=Unit.objects.get(slug='cmpt'))
    r.save()
示例#20
0
def create_others():
    """
    Create other users for the test data set
    """
    p = Person(emplid=fake_emplid(), first_name="Susan", last_name="Kindersley", pref_first_name="sumo", userid="sumo")
    p.save()
    r = Role(person=p, role="GRAD", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    p = Person(emplid=fake_emplid(), first_name="Danyu", last_name="Zhao", pref_first_name="Danyu", userid="dzhao")
    p.save()
    set_privacy_signed(p)
    r = Role(person=p, role="ADVS", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='dixon'), role="PLAN", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='ggbaker'), role="FAC", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='dixon'), role="FAC", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='diana'), role="FAC", unit=Unit.objects.get(slug='cmpt'))
    r.save()

    p = Person.objects.get(userid='ggbaker')
    set_privacy_signed(p)
    r = Role(person=p, role="GRAD", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=p, role="ADMN", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=p, role="TAAD", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=p, role="FUND", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=Person.objects.get(userid='popowich'), role="GRPD", unit=Unit.objects.get(slug='cmpt'))
    r.save()
示例#21
0
def create_others():
    """
    Create other users for the test data set
    """
    p = Person(emplid=fake_emplid(), first_name="Susan", last_name="Kindersley", pref_first_name="sumo", userid="sumo")
    p.save()
    Role(person=p, role="GRPD", unit=Unit.objects.get(slug='cmpt')).save()
    p = Person(emplid=fake_emplid(), first_name="Danyu", last_name="Zhao", pref_first_name="Danyu", userid="dzhao")
    p.save()
    Role(person=p, role="ADVS", unit=Unit.objects.get(slug='cmpt')).save()
    Role(person=p, role="TAAD", unit=Unit.objects.get(slug='cmpt')).save()
    Role(person=p, role="GRAD", unit=Unit.objects.get(slug='cmpt')).save()
    Role(person=p, role="FUND", unit=Unit.objects.get(slug='cmpt')).save()
    Role(person=p, role="ADMN", unit=Unit.objects.get(slug='cmpt')).save()
示例#22
0
文件: tests.py 项目: avacariu/coursys
    def test_roles(self):
        # create person an give sysadmin role
        p1 = Person(emplid=210012345, userid="test1",
                last_name="Lname", first_name="Fname", pref_first_name="Fn", middle_name="M")
        p1.save()
        
        unit = Unit.objects.get(label="UNIV")
        r = Role(person=p1, role="SYSA", unit=unit)
        r.save()
        self.assertEqual( str(r), "Lname, Fname (System Administrator, UNIV)")

        # check the front end
        client = Client()
        client.login_user("test1")

        url = reverse('coredata.views.role_list')
        response = basic_page_tests(self, client, url)
        self.assertContains(response, 'Lname, Fname</a></td><td>System Administrator</td>')

        # add a new role with the front end
        oldcount = Role.objects.filter(role='FAC').count()
        url = reverse('coredata.views.new_role')
        response = basic_page_tests(self, client, url)
        
        response = client.post(url, {'person':'33333333', 'role':'FAC', 'unit': 2})
        self.assertEquals(response.status_code, 200)
        validate_content(self, response.content, url)
        self.assertTrue("could not import DB2 module" in response.content
                        or "could not connect to reporting database" in response.content
                        or "Could not find this emplid." in response.content
                        or "Reporting database access has been disabled" in response.content
                        or "Could not communicate with reporting database" in response.content)

        response = client.post(url, {'person':p1.emplid, 'role':'FAC', 'unit':unit.id})
        self.assertEquals(response.status_code, 302)
        
        # make sure the role is now there
        self.assertEquals( Role.objects.filter(role='FAC').count(), oldcount+1)
示例#23
0
文件: tests.py 项目: avacariu/coursys
def create_greg(unit):
    baker = Person(emplid="123456789", userid="ggbaker", first_name="Greg", last_name="Baker")
    baker.config['privacy_date'] = date(2008,9,9)
    baker.config['privacy_version'] = 1 
    baker.save()
    for role_tuple in ROLE_CHOICES:
        role = Role(person=baker, role=role_tuple[0], unit=unit) 
        role.save()
    return baker
示例#24
0
def generate_submission_contents(activity, z, prefix=''):
    """
    add of of the submissions for this activity to the ZipFile z
    """
    # build dictionary of all most recent submissions by student userid/group slug
    if activity.group:
        submissions = GroupSubmission.objects.filter(
            activity=activity).order_by('created_at').select_related(
                'activity', 'group')
    else:
        submissions = StudentSubmission.objects.filter(
            activity=activity).order_by('created_at').select_related(
                'activity', 'member', 'member__person')

    # group submissions by student/group
    submissions_by_person = {}
    for s in submissions:
        slug = s.file_slug()
        if slug not in submissions_by_person:
            submissions_by_person[slug] = []
        subs = submissions_by_person[slug]
        subs.append(s)

    component_list = select_all_components(activity, include_deleted=True)
    sub_time = {}  # submission times for summary
    # now collect submitted components (and last-submission times for summary)
    for slug in submissions_by_person:
        submission = submissions_by_person[slug]
        last_sub = max([s.created_at for s in submission])
        sub_time[slug] = last_sub
        submitted_components = get_all_submission_components(
            submission, activity, component_list=component_list)
        _add_submission_to_zip(z,
                               submission[-1],
                               submitted_components,
                               prefix=prefix + slug)

    # produce summary of submission datetimes
    slugs = sub_time.keys()
    slugs.sort()
    summarybuffer = StringIO.StringIO()
    summarycsv = csv.writer(summarybuffer)
    summarycsv.writerow([Person.userid_header(), "Last Submission"])
    for s in slugs:
        summarycsv.writerow([s, sub_time[s].strftime("%Y/%m/%d %H:%M:%S")])
    z.writestr(prefix + "summary.csv", summarybuffer.getvalue())
    summarybuffer.close()
示例#25
0
def get_person(emplid, commit=True, force=False, grad_data=False):
    """
    Get/update personal info for this emplid and return (updated & saved) Person object.
    """
    global imported_people
    # use imported_people as a cache
    if emplid in imported_people:
        return imported_people[emplid]

    # either get old or create new Person object
    p_old = Person.objects.filter(emplid=emplid)
    if len(p_old) > 1:
        # should be dead code, since emplid is a unique key in the DB
        raise KeyError("Already duplicate people: %r" % (p_old))
    elif len(p_old) == 1:
        p = p_old[0]
    else:
        p = Person(emplid=emplid)
    imported_people[emplid] = p

    if 'lastimport' in p.config:
        import_age = time.time() - p.config['lastimport']
    else:
        import_age = IMPORT_THRESHOLD * 2

    # active students with no userid: pay more attention to try to get their userid for login/email.
    if p.userid is None and import_age > NO_USERID_IMPORT_THRESHOLD:
        new_p = import_person(p, commit=commit, grad_data=grad_data)
        if new_p:
            return new_p
        elif p_old:
            return p

    # only import if data is older than IMPORT_THRESHOLD (unless forced)
    # Randomly occasionally import anyway, so new students don't stay bunched-up.
    elif not force and import_age < IMPORT_THRESHOLD and random.random(
    ) < 0.99:
        return p

    # actually import their data
    else:
        new_p = import_person(p, commit=commit, grad_data=grad_data)
        if new_p:
            return new_p
        elif p_old:
            return p
示例#26
0
def create_others():
    """
    Create other users for the test data set
    """
    p = Person(emplid=fake_emplid(), first_name="Susan", last_name="Kindersley", pref_first_name="sumo", userid="sumo")
    p.save()
    Role(person=p, role="GRPD", unit=Unit.objects.get(slug='cmpt')).save()
    p = Person(emplid=fake_emplid(), first_name="Danyu", last_name="Zhao", pref_first_name="Danyu", userid="dzhao")
    p.save()
    Role(person=p, role="ADVS", unit=Unit.objects.get(slug='cmpt')).save()
    Role(person=p, role="TAAD", unit=Unit.objects.get(slug='cmpt')).save()
    Role(person=p, role="GRAD", unit=Unit.objects.get(slug='cmpt')).save()
    Role(person=p, role="FUND", unit=Unit.objects.get(slug='cmpt')).save()
    Role(person=p, role="ADMN", unit=Unit.objects.get(slug='cmpt')).save()
示例#27
0
def generate_submission_contents(activity, z, prefix=''):
    """
    add of of the submissions for this activity to the ZipFile z
    """
    # build dictionary of all most recent submissions by student userid/group slug
    if activity.group:
        submissions = GroupSubmission.objects.filter(activity=activity).order_by('created_at').select_related('activity','group')
    else:
        submissions = StudentSubmission.objects.filter(activity=activity).order_by('created_at').select_related('activity','member','member__person')
    
    # group submissions by student/group
    submissions_by_person = {}
    for s in submissions:
        slug = s.file_slug()
        if slug not in submissions_by_person:
            submissions_by_person[slug] = []
        subs = submissions_by_person[slug]
        subs.append(s)
    
    component_list = select_all_components(activity, include_deleted=True)
    sub_time = {} # submission times for summary
    # now collect submitted components (and last-submission times for summary)
    for slug in submissions_by_person:
        submission = submissions_by_person[slug]
        last_sub = max([s.created_at for s in submission])
        sub_time[slug] = last_sub
        submitted_components = get_all_submission_components(submission, activity, component_list=component_list)
        _add_submission_to_zip(z, submission[-1], submitted_components, prefix=prefix+slug)
    
    # produce summary of submission datetimes
    slugs = sub_time.keys()
    slugs.sort()
    summarybuffer = StringIO.StringIO()
    summarycsv = csv.writer(summarybuffer)
    summarycsv.writerow([Person.userid_header(), "Last Submission"])
    for s in slugs:
        summarycsv.writerow([s, sub_time[s].strftime("%Y/%m/%d %H:%M:%S")])
    z.writestr(prefix+"summary.csv", summarybuffer.getvalue())
    summarybuffer.close()
示例#28
0
def create_test_offering():
    """
    Create a CourseOffering (and related stuff) that can be used in tests with no fixtures
    """
    s = create_fake_semester('1144')
    u = Unit(label='BABL', name="Department of Babbling")
    u.save()
    o = CourseOffering(subject='BABL', number='123', section='F104', semester=s, component='LEC', owner=u,
                       title='Babbling for Baferad Ferzizzles', enrl_cap=100, enrl_tot=5, wait_tot=0)
    o.save()

    i = Person(first_name='Insley', last_name='Instructorberg', emplid=20000009, userid='instr')
    i.save()
    s = Person(first_name='Stanley', last_name='Studentson', emplid=20000010, userid='student')
    s.save()

    Member(offering=o, person=i, role='INST').save()
    Member(offering=o, person=s, role='STUD').save()

    return o
示例#29
0
def test_class_1(slug):
    """
    main test course: 20 students, TA, some assignments
    """
    crs = CourseOffering.objects.get(slug=slug)

    crs.set_labtut(True)
    crs.set_url("http://www.cs.sfu.ca/CC/165/common/")
    crs.set_taemail("*****@*****.**")
    crs.save()
    for i in range(10):
        lab = "D1%02i" % (random.randint(1, 4))
        p = Person.objects.get(userid="0aaa%i" % (i))
        if Member.objects.filter(person=p, offering=crs, role="STUD"):
            # randomly added by other student-adder: skip
            continue

        m = Member(person=p,
                   offering=crs,
                   role="STUD",
                   credits=3,
                   career="UGRD",
                   added_reason="AUTO",
                   labtut_section=lab)
        m.save()

    if not Member.objects.filter(
            person__userid='ggbaker', offering=crs, role='INST'):
        Member(person=Person.objects.get(userid='ggbaker'),
               offering=crs,
               role='INST').save()

    # create a TA
    p = Person(emplid=fake_emplid(),
               userid="0grad1",
               last_name="Gradstudent",
               first_name="Douglas",
               middle_name="",
               pref_first_name="Doug")
    p.save()
    m = Member(person=p,
               offering=crs,
               role="TA",
               credits=0,
               career="NONS",
               added_reason="AUTO",
               labtut_section=None)
    m.save()

    # create example activities
    crs.activity_set.all().update(deleted=True)
    a1 = NumericActivity(offering=crs,
                         name="Assignment 1",
                         short_name="A1",
                         status="RLS",
                         due_date=crs.semester.start +
                         datetime.timedelta(days=60),
                         percent=10,
                         group=False,
                         max_grade=10,
                         position=1)
    a1.set_url("http://www.cs.sfu.ca/CC/165/common/a1")
    a1.save()
    a2 = NumericActivity(offering=crs,
                         name="Assignment 2",
                         short_name="A2",
                         status="URLS",
                         due_date=crs.semester.start +
                         datetime.timedelta(days=70),
                         percent=10,
                         group=True,
                         max_grade=20,
                         position=2)
    a2.save()
    pr = LetterActivity(offering=crs,
                        name="Project",
                        short_name="Proj",
                        status="URLS",
                        due_date=crs.semester.start +
                        datetime.timedelta(days=80),
                        percent=40,
                        group=True,
                        position=3)
    pr.save()
    re = LetterActivity(offering=crs,
                        name="Report",
                        short_name="Rep",
                        status="URLS",
                        due_date=crs.semester.start +
                        datetime.timedelta(days=81),
                        percent=10,
                        group=False,
                        position=4)
    re.save()
    ex = NumericActivity(offering=crs,
                         name="Final Exam",
                         short_name="Exam",
                         status="URLS",
                         due_date=None,
                         percent=30,
                         group=False,
                         max_grade=90,
                         position=5)
    ex.save()
    to = CalNumericActivity(offering=crs,
                            name="Final Percent",
                            short_name="Perc",
                            status="INVI",
                            due_date=None,
                            percent=0,
                            group=False,
                            max_grade=100,
                            formula="[[activitytotal]]",
                            position=6)
    to.save()
    to = CalLetterActivity(offering=crs,
                           name="Letter Grade",
                           short_name="Letter",
                           status="INVI",
                           due_date=None,
                           percent=0,
                           group=False,
                           numeric_activity=to,
                           position=6)
    to.save()

    # make A1 submittable and markable
    s = CodeComponent(activity=a1,
                      title="Code File",
                      description="The code you're submitting.",
                      allowed=".py,.java")
    s.save()
    s = PDFComponent(activity=a1,
                     title="Report",
                     description="Report on what you did.",
                     specified_filename="report.pdf")
    s.save()

    m = ActivityComponent(
        numeric_activity=a1,
        max_mark=5,
        title="Part 1",
        description="Part 1 was done well and seems to work.",
        position=1)
    m.save()
    m = ActivityComponent(
        numeric_activity=a1,
        max_mark=5,
        title="Part 2",
        description="Part 2 was done well and seems to work.",
        position=2)
    m.save()

    # create some groups
    g = Group(name="SomeGroup",
              courseoffering=crs,
              manager=Member.objects.get(offering=crs,
                                         person__userid="0aaa0",
                                         role='STUD'))
    g.save()
    for userid in ['0aaa0', '0aaa1', '0aaa5', '0aaa8']:
        gm = GroupMember(group=g,
                         student=Member.objects.get(offering=crs,
                                                    person__userid=userid),
                         confirmed=True,
                         activity=a2)
        gm.save()

    g = Group(name="AnotherGroup",
              courseoffering=crs,
              manager=Member.objects.get(offering=crs, person__userid="0aaa4"))
    g.save()
    for userid in ['0aaa4', '0aaa6', '0aaa7', '0aaa2']:
        gm = GroupMember(group=g,
                         student=Member.objects.get(offering=crs,
                                                    person__userid=userid),
                         confirmed=True,
                         activity=a2)
        gm.save()
        gm = GroupMember(group=g,
                         student=Member.objects.get(offering=crs,
                                                    person__userid=userid),
                         confirmed=True,
                         activity=pr)
        gm.save()
示例#30
0
 def setUp(self):
     p1 = Person(emplid=210012345, userid="test1",
             last_name="Lname", first_name="Fname", pref_first_name="Fn", middle_name="M")
     p1.save()
示例#31
0
文件: tests.py 项目: tjkind/coursys
 def setUp(self):
     """
         Build a TACategory, TAContract, and two TACourses
     """
     unit = Unit(label="TEST", name="A Fake Unit for Testing") 
     unit.save()
     person = Person(emplid="300000000",
                     userid="testy",
                     first_name="Testy",
                     last_name="Testerson")
     person.save()
     semester = Semester(name="1147",
                         start=datetime.date.today(),
                         end=datetime.date.today())
     semester.save()
     course1 = Course(subject="TEST", 
                     number="100",
                     title="Intro to Testing")
     course1.save()
     course2 = Course(subject="TEST", 
                     number="200",
                     title="Advanced Testing")
     course2.save()
     courseoffering1 = CourseOffering(subject="TEST",
                                      number="100",
                                      section="D100",
                                      semester=semester,
                                      component="LEC",
                                      owner=unit,
                                      title="Intro to Testing",
                                      campus="BRNBY",
                                      enrl_cap=100,
                                      enrl_tot=100,
                                      wait_tot=50,
                                      course=course1)
     courseoffering1.save()
     courseoffering2 = CourseOffering(subject="TEST",
                                      number="200",
                                      section="D200",
                                      semester=semester,
                                      component="LEC",
                                      owner=unit,
                                      title="Advanced Testing",
                                      campus="BRNBY",
                                      enrl_cap=100,
                                      enrl_tot=100,
                                      wait_tot=50,
                                      course=course2)
     courseoffering2.save()
     account = Account(unit=unit, 
                       account_number=1337, 
                       position_number=5,
                       title="A Fake Account for Testing")
     account.save()
     four_weeks_later = datetime.date.today() + datetime.timedelta(days=28)
     hiring_semester = HiringSemester(semester=semester,
                               unit=unit,
                               deadline_for_acceptance=datetime.date.today(),
                               pay_start=datetime.date.today(),
                               pay_end=four_weeks_later,
                               payperiods=2.5)
     hiring_semester.save()
     category = TACategory(account=account,
                           hiring_semester=hiring_semester,
                           code="TST",
                           title="Test Contract Category",
                           hours_per_bu=decimal.Decimal("42"),
                           holiday_hours_per_bu=decimal.Decimal("1.1"),
                           pay_per_bu=decimal.Decimal("125.00"),
                           scholarship_per_bu=decimal.Decimal("25.00"),
                           bu_lab_bonus=decimal.Decimal("0.17"))
     category.save()
     contract = TAContract(category=category,
                           person=person,
                           status="NEW",
                           sin="123456789",
                           deadline_for_acceptance=datetime.date.today(),
                           pay_start=datetime.date.today(),
                           pay_end=datetime.date.today() + datetime.timedelta(days=10),
                           payperiods=2.5,
                           appointment="INIT",
                           conditional_appointment=True,
                           created_by="classam",
                           tssu_appointment=True)
     contract.save()
     tacourse = TACourse(course=courseoffering1,
                         contract=contract,
                         bu=decimal.Decimal('3.0'),
                         labtut=True)
     tacourse.save()
     tacourse2 = TACourse(course=courseoffering2,
                          contract=contract,
                          bu=decimal.Decimal('2.0'),
                          labtut=False)
     tacourse2.save()
示例#32
0
def create_coredata():
    """
    Create enough of the coredata.models stuff to run basic tests
    """
    create_units()

    # restore ggbaker's real emplid so import_offerings will match
    p = find_person('ggbaker')
    p.emplid = find_emplid('ggbaker')

    # import a few more people we definitely need later
    find_person('popowich')
    find_person('dixon')
    find_person('diana')
    find_person('dzhao')
    find_person('pba7')

    # import a limited set of course offerings
    offerings = import_offerings(import_semesters=import_strms, extra_where=
        "(subject='CMPT' AND (catalog_nbr LIKE '%% 12%%')) "
        "OR (subject='ENSC' AND (catalog_nbr LIKE '%% 10%%')) "
        )
    offerings = list(offerings)
    offerings.sort()

    if not CourseOffering.objects.filter(slug=TEST_COURSE_SLUG):
        o = CourseOffering.objects.filter(subject='CMPT', semester__name=import_strms()[0]) \
            .order_by('number', 'section').first()
        raise ValueError, "courselib.testing.TEST_COURSE_SLUG isn't an offering we have. Maybe use '%s'." % (o.slug)

    # import instructors
    for o in offerings:
        import_offering_members(o, students=False)

    # try to guess instructors' userids
    for p in Person.objects.filter(userid__isnull=True):
        p.userid = guess_userid(p.emplid)
        p.save()

    fake_emplids()

    # use/import no real emplids after this

    # create some fake undergrad/grad students
    for i in range(20):
        userid = "0aaa%i" % (i)
        fname = randname(8)
        p = random.randint(1,2)
        if p == 1:
            pref = fname[:4]
        else:
            pref = fname
        p = Person(emplid=300000300+i, userid=userid, last_name='Student', first_name=fname, middle_name=randname(6), pref_first_name=pref)
        p.save()

        userid = "0ggg%i" % (i)
        fname = randname(8)
        p = random.randint(1,2)
        if p == 1:
            pref = fname[:4]
        else:
            pref = fname
        p = Person(emplid=300000500+i, userid=userid, last_name='Grad', first_name=fname, middle_name=randname(6), pref_first_name=pref)
        p.config['gender'] = random.choice(('M','F','U'))
        p.config['gpa'] = round(random.triangular(0.0, 4.33, 2.33), 2)
        p.config['visa'] = random.choice([x for x,_ in VISA_STATUSES])
        p.config['citizen'] = random.choice(('Canadian', 'OtherCountrian'))
        p.save()

    # some memberships/roles/etc assumed by tests
    o = CourseOffering.objects.get(slug=TEST_COURSE_SLUG)
    ensure_member(Person.objects.get(userid='ggbaker'), o, "INST", 0, "AUTO", "NONS")
    ensure_member(Person.objects.get(userid='0ggg0'), o, "TA", 0, "AUTO", "NONS")
    ensure_member(Person.objects.get(userid='0aaa0'), o, "STUD", 3, "AUTO", "UGRD")
    ensure_member(Person.objects.get(userid='0aaa1'), o, "STUD", 3, "AUTO", "UGRD")

    d = Person.objects.get(userid='dzhao')
    set_privacy_signed(d)
    r1 = Role(person=d, role='ADVS', unit=Unit.objects.get(slug='cmpt'))
    r1.save()
    r2 = Role(person=d, role='ADMN', unit=Unit.objects.get(slug='cmpt'))
    r2.save()
    r3 = Role(person=Person.objects.get(userid='pba7'), role='SYSA', unit=Unit.objects.get(slug='univ'))
    r3.save()

    # ensures course appears in menu for students
    a = NumericActivity(offering=o, name='Assignment 1', short_name='A1', status='URLS', position=1, percent=10,
        max_grade=10, due_date=(o.semester.start + datetime.timedelta(days=60)))
    a.save()

    return itertools.chain(
        SemesterWeek.objects.filter(semester__name__gt=SEMESTER_CUTOFF),
        Unit.objects.all(),
        Course.objects.all(),
        CourseOffering.objects.all(),
        Person.objects.order_by('emplid'),
        Member.objects.all(),
        [r1, r2, r3, a.activity_ptr, a],
    )
示例#33
0
def manage_tas(request, course_slug):
    course = get_object_or_404(CourseOffering, slug=course_slug)
    longform = False
    if not Member.objects.filter(offering=course,
                                 person__userid=request.user.username,
                                 role="INST"):
        # only instructors can manage TAs
        return ForbiddenResponse(request, "Only instructors can manage TAs")

    if request.method == 'POST' and 'action' in request.POST and request.POST[
            'action'] == 'add':
        form = TAForm(offering=course, data=request.POST)
        if form.non_field_errors():
            # have an unknown userid
            longform = True
        elif form.is_valid():
            userid = form.cleaned_data['userid']
            if not Person.objects.filter(userid=userid) \
                    and form.cleaned_data['fname'] and form.cleaned_data['lname']:
                # adding a new person: handle that.
                eid = 1
                # search for an unused temp emplid
                while True:
                    emplid = "%09i" % (eid)
                    if not Person.objects.filter(emplid=emplid):
                        break
                    eid += 1
                p = Person(first_name=form.cleaned_data['fname'],
                           pref_first_name=form.cleaned_data['fname'],
                           last_name=form.cleaned_data['lname'],
                           middle_name='',
                           userid=userid,
                           emplid=emplid)
                p.save()

            else:
                p = Person.objects.get(userid=userid)

            m = Member(person=p,
                       offering=course,
                       role="TA",
                       credits=0,
                       career="NONS",
                       added_reason="TAIN")
            m.save()

            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                         description=("TA added by instructor: %s for %s") %
                         (userid, course),
                         related_object=m)
            l.save()
            messages.success(request, 'Added %s as a TA.' % (p.name()))
            return HttpResponseRedirect(
                reverse(manage_tas, kwargs={'course_slug': course.slug}))

    elif request.method == 'POST' and 'action' in request.POST and request.POST[
            'action'] == 'del':
        userid = request.POST['userid']
        ms = Member.objects.filter(person__userid=userid,
                                   offering=course,
                                   role="TA",
                                   added_reason="TAIN")
        if ms:
            m = ms[0]
            m.role = "DROP"
            m.save()
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                         description=("TA removed by instructor: %s for %s") %
                         (userid, course),
                         related_object=m)
            l.save()
            messages.success(request,
                             'Removed %s as a TA.' % (m.person.name()))
        return HttpResponseRedirect(
            reverse(manage_tas, kwargs={'course_slug': course.slug}))

    else:
        form = TAForm(offering=course)

    tas = Member.objects.filter(role="TA", offering=course)
    context = {
        'course': course,
        'form': form,
        'tas': tas,
        'longform': longform
    }
    return render(request, 'coredata/manage_tas.html', context)
示例#34
0
文件: tests.py 项目: csvenja/coursys
    def test_person(self):
        """
        Basics of Person objects.
        """
        # create some people to test with
        p1 = Person(emplid=210012345,
                    userid="test1",
                    last_name="Lname",
                    first_name="Fname",
                    pref_first_name="Fn",
                    middle_name="M")
        p2 = Person(emplid=210012346,
                    userid="test2",
                    last_name="Lname",
                    first_name="Zname",
                    pref_first_name="Gn",
                    middle_name="M")
        p3 = Person(emplid=210012347,
                    userid="test3",
                    last_name="Zname",
                    first_name="Fname",
                    pref_first_name="Gn",
                    middle_name="M")
        p3.save()
        p1.save()
        p2.save()

        self.assertEquals(str(p1), "Lname, Fname")
        self.assertEquals(p1.name(), "Fname Lname")
        self.assertEquals(p1.email(), "*****@*****.**")
        people = Person.objects.filter(userid__startswith="test")
        # check sorting
        self.assertEquals(p1, people[0])
        self.assertEquals(p2, people[1])
        self.assertEquals(p3, people[2])

        # uniqueness checking for emplid and userid
        px = Person(emplid=210012345, userid="test4")
        self.assertRaises(IntegrityError, px.save)
示例#35
0
    def handle(self, *args, **options):
        assert settings.DEPLOY_MODE != 'production'

        # import public data dumped from production
        with transaction.atomic():
            for obj in serializers.deserialize(
                    'json',
                    open(options['data_file'], 'rt', encoding='utf8').read()):
                obj.save()

        # create fake students and a TA in every offering
        with transaction.atomic():
            fake_students = [
                Person(emplid=str(500000000 + i),
                       userid='fake%03i' % (i, ),
                       last_name='Fake',
                       first_name=random_name(8),
                       middle_name=random_name(5),
                       title=random.choice(['Mr', 'M', 'Ms', 'Dr']))
                for i in range(n_fake_students)
            ]
            for p in fake_students:
                p.pref_first_name = random.choice([None, p.first_name[:4]])
                p.save()

            fake_grads = [
                Person(emplid=str(510000000 + i),
                       userid='grad%03i' % (i, ),
                       last_name='Grad',
                       first_name=random_name(8),
                       middle_name=random_name(5),
                       title=random.choice(['Mr', 'M', 'Ms', 'Dr']))
                for i in range(n_fake_grads)
            ]
            for p in fake_grads:
                p.pref_first_name = random.choice([None, p.first_name[:4]])
                p.save()

            for o in CourseOffering.objects.all():
                ta_person = random.choice(fake_grads)
                m = Member(person=ta_person,
                           offering=o,
                           role='TA',
                           added_reason='AUTO',
                           credits=0,
                           career='NONS')
                m.save()
                student_people = set(
                    random.choices(fake_students, k=students_per_class))
                for p in student_people:
                    m = Member(person=p,
                               offering=o,
                               role='STUD',
                               added_reason='AUTO',
                               credits=3,
                               career='UGRD')
                    m.save()

            r = Role(person=Person.objects.get(userid='ggbaker'),
                     role='SYSA',
                     unit=Unit.objects.get(label='UNIV'),
                     expiry=datetime.date.today() +
                     datetime.timedelta(days=730))
            r.save()
示例#36
0
文件: views.py 项目: avacariu/coursys
def manage_tas(request, course_slug):
    course = get_object_or_404(CourseOffering, slug=course_slug)
    longform = False
    if not Member.objects.filter(offering=course, person__userid=request.user.username, role="INST"):
        # only instructors can manage TAs
        return ForbiddenResponse(request, "Only instructors can manage TAs")
    
    if request.method == 'POST' and 'action' in request.POST and request.POST['action']=='add':
        form = TAForm(offering=course, data=request.POST)
        if form.non_field_errors():
            # have an unknown userid
            longform = True
        elif form.is_valid():
            userid = form.cleaned_data['userid']
            if not Person.objects.filter(userid=userid) \
                    and form.cleaned_data['fname'] and form.cleaned_data['lname']:
                # adding a new person: handle that.
                eid = 1
                # search for an unused temp emplid
                while True:
                    emplid = "%09i" % (eid)
                    if not Person.objects.filter(emplid=emplid):
                        break
                    eid += 1
                p = Person(first_name=form.cleaned_data['fname'], pref_first_name=form.cleaned_data['fname'], last_name=form.cleaned_data['lname'], middle_name='', userid=userid, emplid=emplid)
                p.save()

            else:
                p = Person.objects.get(userid=userid)

            m = Member(person=p, offering=course, role="TA", credits=0, career="NONS", added_reason="TAIN")
            m.save()
                
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("TA added by instructor: %s for %s") % (userid, course),
                  related_object=m)
            l.save()
            messages.success(request, 'Added %s as a TA.' % (p.name()))
            return HttpResponseRedirect(reverse(manage_tas, kwargs={'course_slug': course.slug}))
            

    elif request.method == 'POST' and 'action' in request.POST and request.POST['action']=='del':
        userid = request.POST['userid']
        ms = Member.objects.filter(person__userid=userid, offering=course, role="TA", added_reason="TAIN")
        if ms:
            m = ms[0]
            m.role = "DROP"
            m.save()
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("TA removed by instructor: %s for %s") % (userid, course),
                  related_object=m)
            l.save()
            messages.success(request, 'Removed %s as a TA.' % (m.person.name()))
        return HttpResponseRedirect(reverse(manage_tas, kwargs={'course_slug': course.slug}))

    else:
        form = TAForm(offering=course)

    tas = Member.objects.filter(role="TA", offering=course)
    context = {'course': course, 'form': form, 'tas': tas, 'longform': longform}
    return render(request, 'coredata/manage_tas.html', context)
示例#37
0
def generate_submission_contents(activity, z, prefix=''):
    """
    add of of the submissions for this activity to the ZipFile z
    """
    from submission.models.gittag import GitTagComponent
    # build dictionary of all most recent submissions by student userid/group slug
    if activity.group:
        submissions = GroupSubmission.objects.filter(
            activity=activity).order_by('created_at').select_related(
                'activity', 'group')
    else:
        submissions = StudentSubmission.objects.filter(
            activity=activity).order_by('created_at').select_related(
                'activity', 'member', 'member__person')

    # group submissions by student/group
    submissions_by_person = {}
    for s in submissions:
        slug = s.file_slug()
        if slug not in submissions_by_person:
            submissions_by_person[slug] = []
        subs = submissions_by_person[slug]
        subs.append(s)

    component_list = select_all_components(activity, include_deleted=True)
    sub_time = {}  # submission times for summary
    # Manage a collection of git tag submission data we see, to produce clone-all script.
    any_git_tags = any(isinstance(c, GitTagComponent) for c in component_list)
    git_tags = []
    # now collect submitted components (and last-submission times for summary)
    for slug in submissions_by_person:
        submission = submissions_by_person[slug]
        last_sub = max([s.created_at for s in submission])
        sub_time[slug] = last_sub
        submitted_components = get_all_submission_components(
            submission, activity, component_list=component_list)
        _add_submission_to_zip(z,
                               submission[-1],
                               submitted_components,
                               prefix=prefix + slug,
                               slug=slug)
        git_tags.extend((comp.slug, slug, sub.url, sub.tag)
                        for comp, sub in submitted_components
                        if isinstance(comp, GitTagComponent) and sub)

    # produce summary of submission datetimes
    slugs = sub_time.keys()
    slugs.sort()
    summarybuffer = StringIO.StringIO()
    summarycsv = csv.writer(summarybuffer)
    summarycsv.writerow([Person.userid_header(), "Last Submission"])
    for s in slugs:
        summarycsv.writerow([s, sub_time[s].strftime("%Y/%m/%d %H:%M:%S")])
    z.writestr(prefix + "summary.csv", summarybuffer.getvalue())
    summarybuffer.close()

    # produce git clone-all script
    if any_git_tags:
        script = [
            '#!/bin/sh', '',
            '# This script will clone all of the submitted git tags for this activity,',
            '# putting them into the current directory. This should work in a Linux, OSX,',
            '# or the Git Bash shell in Windows.', ''
        ]

        git_tags.sort()
        for comp_slug, sub_slug, url, tag in git_tags:
            dir_name = comp_slug + '_' + sub_slug
            script.append(
                'git clone %s %s && \\\n  (cd %s && git checkout tags/%s)' %
                (quote(url), quote(dir_name), quote(dir_name), quote(tag)))

        script.append('')
        z.writestr(prefix + "clone-all.sh", '\n'.join(script))
示例#38
0
def create_coredata():
    """
    Create enough of the coredata.models stuff to run basic tests
    """
    create_units()

    # restore ggbaker's real emplid so import_offerings will match
    p = find_person('ggbaker')
    p.emplid = find_emplid('ggbaker')

    # import a few more people we definitely need later
    find_person('popowich')
    find_person('dixon')
    find_person('diana')
    find_person('dzhao')
    find_person('pba7')

    # import a limited set of course offerings
    offerings = import_offerings(
        import_semesters=import_strms,
        extra_where="(subject='CMPT' AND (catalog_nbr LIKE '%% 12%%')) "
        "OR (subject='CMPT' AND (catalog_nbr LIKE '%% 16%%')) "
        "OR (subject='ENSC' AND (catalog_nbr LIKE '%% 10%%')) ")
    offerings = list(offerings)
    offerings.sort()

    if not CourseOffering.objects.filter(slug=TEST_COURSE_SLUG):
        o = CourseOffering.objects.filter(subject='CMPT', semester__name=import_strms()[0]) \
            .order_by('number', 'section').first()
        raise ValueError, "courselib.testing.TEST_COURSE_SLUG isn't an offering we have. Maybe use '%s'." % (
            o.slug)

    # import instructors
    for o in offerings:
        import_offering_members(o, students=False)

    # try to guess instructors' userids
    for p in Person.objects.filter(userid__isnull=True):
        p.userid = guess_userid(p.emplid)
        p.save()

    fake_emplids()

    # use/import no real emplids after this

    # create some fake undergrad/grad students
    for i in range(20):
        userid = "0aaa%i" % (i)
        fname = randname(8)
        p = random.randint(1, 2)
        if p == 1:
            pref = fname[:4]
        else:
            pref = fname
        p = Person(emplid=300000300 + i,
                   userid=userid,
                   last_name='Student',
                   first_name=fname,
                   middle_name=randname(6),
                   pref_first_name=pref)
        p.save()

        userid = "0ggg%i" % (i)
        fname = randname(8)
        p = random.randint(1, 2)
        if p == 1:
            pref = fname[:4]
        else:
            pref = fname
        p = Person(emplid=300000500 + i,
                   userid=userid,
                   last_name='Grad',
                   first_name=fname,
                   middle_name=randname(6),
                   pref_first_name=pref)
        p.config['gender'] = random.choice(('M', 'F', 'U'))
        p.config['gpa'] = round(random.triangular(0.0, 4.33, 2.33), 2)
        p.config['visa'] = random.choice([x for x, _ in VISA_STATUSES])
        p.config['citizen'] = random.choice(('Canadian', 'OtherCountrian'))
        p.save()

    # some memberships/roles/etc assumed by tests
    o = CourseOffering.objects.get(slug=TEST_COURSE_SLUG)
    ensure_member(Person.objects.get(userid='ggbaker'), o, "INST", 0, "AUTO",
                  "NONS")
    ensure_member(Person.objects.get(userid='0ggg0'), o, "TA", 0, "AUTO",
                  "NONS")
    ensure_member(Person.objects.get(userid='0aaa0'), o, "STUD", 3, "AUTO",
                  "UGRD")
    ensure_member(Person.objects.get(userid='0aaa1'), o, "STUD", 3, "AUTO",
                  "UGRD")

    d = Person.objects.get(userid='dzhao')
    set_privacy_signed(d)
    u = Unit.objects.get(slug='cmpt')
    r1 = Role(person=d, role='ADVS', unit=u, expiry=role_expiry)
    r1.save()
    r2 = Role(person=d, role='ADMN', unit=u, expiry=role_expiry)
    r2.save()
    r3 = Role(person=Person.objects.get(userid='pba7'),
              role='SYSA',
              unit=Unit.objects.get(slug='univ'),
              expiry=role_expiry)
    r3.save()
    r4 = Role(person=d, role='INV', unit=u, expiry=role_expiry)
    r4.save()
    r5 = Role(person=d, role='OUTR', unit=u, expiry=role_expiry)
    r5.save()

    # ensures course appears in menu for students
    a = NumericActivity(offering=o,
                        name=u'Assignmenț 1',
                        short_name='A1',
                        status='URLS',
                        position=1,
                        percent=10,
                        max_grade=10,
                        due_date=(o.semester.start +
                                  datetime.timedelta(days=60)))
    a.save()

    return itertools.chain(
        SemesterWeek.objects.filter(semester__name__gt=SEMESTER_CUTOFF),
        Unit.objects.all(),
        Course.objects.all(),
        CourseOffering.objects.all(),
        Person.objects.order_by('emplid'),
        Member.objects.all(),
        [r1, r2, r3, r4, r5, a.activity_ptr, a],
    )
示例#39
0
文件: tests.py 项目: avacariu/coursys
 def test_person(self):
     """
     Basics of Person objects.
     """
     # create some people to test with
     p1 = Person(emplid=210012345, userid="test1",
             last_name="Lname", first_name="Fname", pref_first_name="Fn", middle_name="M")
     p2 = Person(emplid=210012346, userid="test2",
             last_name="Lname", first_name="Zname", pref_first_name="Gn", middle_name="M")
     p3 = Person(emplid=210012347, userid="test3",
             last_name="Zname", first_name="Fname", pref_first_name="Gn", middle_name="M")
     p3.save()
     p1.save()
     p2.save()
     
     self.assertEquals(str(p1), "Lname, Fname")
     self.assertEquals(p1.name(), "Fname Lname")
     self.assertEquals(p1.email(), "*****@*****.**")
     people = Person.objects.filter(userid__startswith="test")
     # check sorting
     self.assertEquals(p1, people[0])
     self.assertEquals(p2, people[1])
     self.assertEquals(p3, people[2])
     
     # uniqueness checking for emplid and userid
     px = Person(emplid=210012345, userid="test4")
     self.assertRaises(IntegrityError, px.save)
示例#40
0
def main():
    for strm in NEEDED_SEMESTERS:
        create_fake_semester(strm)
    create_units()

    print "importing course offerings"
    # get very few courses here so there isn't excess data hanging around
    offerings = import_offerings(
        import_semesters=import_semesters,
        create_units=True,
        extra_where=
        #"(subject='CMPT' AND (catalog_nbr LIKE '%%165%%')) "
        #"OR (subject='ENSC' AND (catalog_nbr LIKE '%% 100%%')) "
        "(subject='CMPT' AND (catalog_nbr LIKE '%% 1%%' OR catalog_nbr LIKE '%% 2%%')) "
        "OR (subject='ENSC' AND (catalog_nbr LIKE '%% 2_5%%')) ")
    offerings = list(offerings)
    offerings.sort()

    print "importing course members"
    for o in offerings:
        import_offering_members(o, students=False)

    # should now have all the "real" people: fake their emplids
    fake_emplids()

    # make sure these people are here, since we need them
    if not Person.objects.filter(userid='ggbaker'):
        Person(userid='ggbaker',
               first_name='Gregory',
               last_name='Baker',
               emplid='000001233').save()
    if not Person.objects.filter(userid='dixon'):
        Person(userid='dixon',
               first_name='Tony',
               last_name='Dixon',
               emplid='000001234').save()
    if not Person.objects.filter(userid='diana'):
        Person(userid='diana',
               first_name='Diana',
               last_name='Cukierman',
               emplid='000001235').save()
    if not Person.objects.filter(userid='popowich'):
        Person(userid='popowich',
               first_name='Fred',
               last_name='Popowich',
               emplid='000001236').save()

    print "creating fake classess"
    create_classes()
    create_test_classes()

    print "creating other data"
    create_others()
    create_grad_templ()
    create_more_data()
    create_form_data()
    combine_sections(get_combined())

    print "creating grad students"
    create_grads()
    create_ta_data()
    create_ra_data()

    print "giving sysadmin permissions"
    give_sysadmin(['ggbaker', 'sumo'])

    serialize("new-test.json")
示例#41
0
文件: tests.py 项目: avacariu/coursys
 def setUp(self):
     """
         Build a TACategory, TAContract, and two TACourses
     """
     unit = Unit(label="TEST", name="A Fake Unit for Testing") 
     unit.save()
     person = Person(emplid="300000000",
                     userid="testy",
                     first_name="Testy",
                     last_name="Testerson")
     person.save()
     semester = Semester(name="1147",
                         start=datetime.date.today(),
                         end=datetime.date.today())
     semester.save()
     course1 = Course(subject="TEST", 
                     number="100",
                     title="Intro to Testing")
     course1.save()
     course2 = Course(subject="TEST", 
                     number="200",
                     title="Advanced Testing")
     course2.save()
     courseoffering1 = CourseOffering(subject="TEST",
                                      number="100",
                                      section="D100",
                                      semester=semester,
                                      component="LEC",
                                      owner=unit,
                                      title="Intro to Testing",
                                      campus="BRNBY",
                                      enrl_cap=100,
                                      enrl_tot=100,
                                      wait_tot=50,
                                      course=course1)
     courseoffering1.save()
     courseoffering2 = CourseOffering(subject="TEST",
                                      number="200",
                                      section="D200",
                                      semester=semester,
                                      component="LEC",
                                      owner=unit,
                                      title="Advanced Testing",
                                      campus="BRNBY",
                                      enrl_cap=100,
                                      enrl_tot=100,
                                      wait_tot=50,
                                      course=course2)
     courseoffering2.save()
     account = Account(unit=unit, 
                       account_number=1337, 
                       position_number=5,
                       title="A Fake Account for Testing")
     account.save()
     four_weeks_later = datetime.date.today() + datetime.timedelta(days=28)
     hiring_semester = HiringSemester(semester=semester,
                               unit=unit,
                               deadline_for_acceptance=datetime.date.today(),
                               pay_start=datetime.date.today(),
                               pay_end=four_weeks_later,
                               payperiods=2.5)
     hiring_semester.save()
     category = TACategory(account=account,
                           hiring_semester=hiring_semester,
                           code="TST",
                           title="Test Contract Category",
                           hours_per_bu=decimal.Decimal("42"),
                           holiday_hours_per_bu=decimal.Decimal("1.1"),
                           pay_per_bu=decimal.Decimal("100.00"),
                           scholarship_per_bu=decimal.Decimal("25.00"),
                           bu_lab_bonus=decimal.Decimal("0.17"))
     category.save()
     contract = TAContract(category=category,
                           person=person,
                           status="NEW",
                           sin="123456789",
                           deadline_for_acceptance=datetime.date.today(),
                           pay_start=datetime.date.today(),
                           pay_end=datetime.date.today() + datetime.timedelta(days=10),
                           payperiods=2.5,
                           appointment="INIT",
                           conditional_appointment=True,
                           created_by="classam",
                           tssu_appointment=True)
     contract.save()
     tacourse = TACourse(course=courseoffering1,
                         contract=contract,
                         bu=decimal.Decimal('3.0'),
                         labtut=True)
     tacourse.save()
     tacourse2 = TACourse(course=courseoffering2,
                          contract=contract,
                          bu=decimal.Decimal('2.0'),
                          labtut=False)
     tacourse2.save()
示例#42
0
    def generate_submission_contents(self, z, prefix='', always_summary=True):
        """
        Assemble submissions and put in ZIP file.
        """
        self.ensure_components()
        assert self.submissions is not None
        assert self.all_submitted_components is not None

        multi = self.activity.multisubmit()

        from submission.models.gittag import GitTagComponent
        any_git_tags = any(
            isinstance(c, GitTagComponent) for c in self.components)
        git_tags = []

        # Collect all of the SubmittedComponents that we need to output
        # i.e. the most recent of each by student|group and component
        found = set(
        )  # (student|group, SubmissionComponent) pairs we have already included
        individual_subcomps = {
        }  # student|group: [(SubmissionComponent, SubmittedComponent)]
        last_submission = {}  # student|group: final Submission
        for sub, subcomps in self.submissions_and_components():
            slug = sub.file_slug()
            for comp, sc in subcomps:
                key = (slug, comp.slug)
                if (not multi and key in found) or sc is None:
                    continue

                if slug not in last_submission:
                    last_submission[slug] = sub

                found.add(key)

                scs = individual_subcomps.get(slug, [])
                scs.append((comp, sc))

                individual_subcomps[sub.file_slug()] = scs

        # Now add them to the ZIP
        for slug, subcomps in individual_subcomps.items():
            lastsub = last_submission[slug]
            p = os.path.join(prefix, slug)
            self._add_to_zip(z,
                             self.activity,
                             subcomps,
                             lastsub.created_at,
                             slug=lastsub.file_slug(),
                             prefix=p,
                             multi=multi)

            git_tags.extend((comp.slug, slug, sub.url, sub.tag)
                            for comp, sub in subcomps
                            if isinstance(comp, GitTagComponent) and sub)

        # produce summary of submission datetimes
        if found or always_summary:
            slugs = list(last_submission.keys())
            slugs.sort()
            summarybuffer = io.StringIO()
            summarycsv = csv.writer(summarybuffer)
            summarycsv.writerow([Person.userid_header(), "Last Submission"])
            for s in slugs:
                summarycsv.writerow([
                    s,
                    last_submission[s].created_at.strftime("%Y/%m/%d %H:%M:%S")
                ])
            z.writestr(prefix + "summary.csv", summarybuffer.getvalue())
            summarybuffer.close()

        # produce git clone-all script
        if any_git_tags:
            script = [
                '#!/bin/sh', '',
                '# This script will clone all of the submitted git tags for this activity,',
                '# putting them into the current directory. This should work in a Linux, OSX,',
                '# or the Git Bash shell in Windows.', ''
            ]

            git_tags.sort()
            for comp_slug, sub_slug, url, tag in git_tags:
                dir_name = comp_slug + '_' + sub_slug
                script.append(
                    'git clone %s %s && \\\n  (cd %s && git checkout tags/%s)'
                    %
                    (quote(url), quote(dir_name), quote(dir_name), quote(tag)))

            script.append('')
            z.writestr(prefix + "clone-all.sh", '\n'.join(script))
示例#43
0
def create_more_data():
    """
    More data for the unit tests and general usabilty of a test system
    """
    templates = [
        {
            "field":
            "contact_email_text",
            "label":
            "generic",
            "text":
            "DESCRIPTION OF INCIDENT. This does not usually occur unless there is a violation of SFU's Code of Academic Integrity and Good Conduct, Policy S10.01. I take academic honesty very seriously and intend to pursue this apparent violation of SFU's standards for academic honesty.\r\n\r\nAs required by SFU Policy S10.02, Principles and Procedures for Academic Discipline, I am offering you the opportunity to meet with me to discuss this incident. You are not required to accept this offer. If you would like to meet, please contact me to make an appointment outside of my regular office hours.\r\n\r\nYou may wish to refer to SFU's policies and procedures on academic integrity,\r\n  http://www.sfu.ca/policies/Students/index.html .\r\nYou can also contact the Office of the Ombudsperson for assistance in navigating University procedures.\r\n"
        },
        {
            "field":
            "contact_email_text",
            "label":
            "not your work",
            "text":
            "Your submission for {{ACTIVITIES}} contains work that does not appear to be your own. This indicates that there is a violation of SFU's Code of Academic Integrity and Good Conduct, Policy S10.01. I take academic honesty very seriously and intend to pursue this apparent violation of SFU's standards for academic honesty.\r\n\r\nAs required by SFU Policy S10.02, Principles and Procedures for Academic Discipline, I am offering you the opportunity to meet with me to discuss this incident. You are not required to accept this offer. If you would like to meet, please contact me to make an appointment outside of my regular office hours.\r\n\r\nYou may wish to refer to SFU's policies and procedures on academic integrity,\r\n  http://www.sfu.ca/policies/Students/index.html .\r\nYou can also contact the Office of the Ombudsperson for assistance in navigating University procedures.\r\n"
        },
        {
            "field": "facts",
            "label": "attachment",
            "text": "See details in attached file facts.pdf."
        },
        {
            "field":
            "contact_email_text",
            "label":
            "simiar work (group)",
            "text":
            "You and other students submitted very similar work on {{ACTIVITIES}}. This level of similarity does not usually occur unless collaboration exceeds the limits allowed by SFU's Code of Academic Integrity and Good Conduct, Policy S10.01. I take academic honesty very seriously and intend to pursue this apparent violation of SFU's standards for academic honesty.\r\n\r\nAs required by SFU Policy S10.02, Principles and Procedures for Academic Discipline, I am offering you the opportunity to meet with me to discuss this incident. You are not required to accept this offer. If you would like to meet, please contact me to make an appointment outside of my regular office hours.\r\n\r\nYou may wish to refer to SFU's policies and procedures on academic integrity,\r\n  http://www.sfu.ca/policies/Students/index.html .\r\nYou can also contact the Office of the Ombudsperson for assistance in navigating University procedures.\r\n"
        },
        {
            "field":
            "facts",
            "label":
            "copied (other knew)",
            "text":
            "{{FNAME}} was given a solution to {{ACTIVITIES}} by another student. The other student seems to have completed the work independently. Both students submitted the work as their own."
        },
        {
            "field":
            "facts",
            "label":
            "copied (without knowledge)",
            "text":
            "{{FNAME}} copied the work of another student on {{ACTIVITIES}} without his/her knowledge.  Both students submitted the work as their own."
        },
        {
            "field":
            "meeting_summary",
            "label":
            "admitted",
            "text":
            u"The student admitted academic dishonesty as described below in \u201cfacts of the case\u201d."
        },
        {
            "field":
            "meeting_summary",
            "label":
            "quote email",
            "text":
            "The student explained the situation in his/her email:\r\n\r\nbq. PASTE QUOTE HERE"
        },
        {
            "field": "meeting_summary",
            "label": "explained",
            "text": "{{FNAME}} explained that..."
        },
    ]
    for data in templates:
        t = DisciplineTemplate(**data)
        t.save()

    cmpt = Unit.objects.get(slug='cmpt')
    a = Account(account_number=12345,
                position_number=12345,
                title='MSc TA',
                unit=cmpt)
    a.save()
    a = Account(account_number=12346,
                position_number=12346,
                title='PhD TA',
                unit=cmpt)
    a.save()
    a = Account(account_number=12347,
                position_number=12347,
                title='External TA',
                unit=cmpt)
    a.save()
    a = Account(account_number=12348,
                position_number=12348,
                title='Undergrad TA',
                unit=cmpt)
    a.save()

    uc = UserConfig(user=Person.objects.get(userid='dzhao'),
                    key='advisor-token',
                    value={'token': '30378700c0091f34412ec9a082dca267'})
    uc.save()
    uc = UserConfig(user=Person.objects.get(userid='ggbaker'),
                    key='advisor-token',
                    value={'token': '082dca26730378700c0091f34412ec9a'})
    uc.save()
    p = Person(userid='probadmn',
               emplid='200002387',
               first_name='Problem',
               last_name='Admin')
    p.save()
    uc = UserConfig(user=p,
                    key='problems-token',
                    value={'token': '30378700c0091f34412ec9a082dca268'})
    uc.save()

    p = Person(userid='teachadm',
               emplid='200002388',
               first_name='Teaching',
               last_name='Admin')
    p.save()
    r = Role(person=p, role="TADM", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    #sp = SemesterPlan(semester=Semester.objects.get(name=TEST_SEMESTER), name='Test Plan', unit=Unit.objects.get(slug='cmpt'), slug='test-plan')
    #sp.save()
    #o = PlannedOffering(plan=sp, course=Course.objects.get(slug='cmpt-102'), section='D100', campus='BRNBY', enrl_cap=100)
    #o.save()
    #PlanningCourse.create_for_unit(Unit.objects.get(slug='cmpt'))
    #te = TeachingEquivalent(pk=1, instructor=Person.objects.get(userid='ggbaker'), semester=Semester.objects.get(name=TEST_SEMESTER), credits_numerator=1, credits_denominator=1, summary="Foo", status='UNCO')
    #te.save()
    #ti = TeachingIntention(instructor=Person.objects.get(userid='ggbaker'), semester=Semester.objects.get(name=TEST_SEMESTER), count=2)
    #ti.save()
    #tc = TeachingCapability(instructor=Person.objects.get(userid='ggbaker'), course=Course.objects.get(slug='cmpt-102'), note='foo')
    #tc.save()

    p = Person(userid='classam',
               emplid='200002389',
               first_name='Curtis',
               last_name='Lassam')
    p.save()
    r = Role(person=p, role="TECH", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=p, role="SYSA", unit=Unit.objects.get(slug='cmpt'))
    r.save()

    # create some faculty roles
    members = Member.objects.filter(role='INST', offering__owner__slug='cmpt')
    instr = set(m.person for m in members)
    faculty = random.sample(instr, 10)
    for p in faculty:
        Role.objects.get_or_create(person=p, role='FAC', unit=cmpt)
示例#44
0
def create_more_data():
    """
    More data for the unit tests and general usabilty of a test system
    """
    templates = [
                 {"field": "contact_email_text",
                  "label": "generic",
                  "text": "DESCRIPTION OF INCIDENT. This does not usually occur unless there is a violation of SFU's Code of Academic Integrity and Good Conduct, Policy S10.01. I take academic honesty very seriously and intend to pursue this apparent violation of SFU's standards for academic honesty.\r\n\r\nAs required by SFU Policy S10.02, Principles and Procedures for Academic Discipline, I am offering you the opportunity to meet with me to discuss this incident. You are not required to accept this offer. If you would like to meet, please contact me to make an appointment outside of my regular office hours.\r\n\r\nYou may wish to refer to SFU's policies and procedures on academic integrity,\r\n  http://www.sfu.ca/policies/Students/index.html .\r\nYou can also contact the Office of the Ombudsperson for assistance in navigating University procedures.\r\n"},
                 {"field": "contact_email_text",
                  "label": "not your work",
                  "text": "Your submission for {{ACTIVITIES}} contains work that does not appear to be your own. This indicates that there is a violation of SFU's Code of Academic Integrity and Good Conduct, Policy S10.01. I take academic honesty very seriously and intend to pursue this apparent violation of SFU's standards for academic honesty.\r\n\r\nAs required by SFU Policy S10.02, Principles and Procedures for Academic Discipline, I am offering you the opportunity to meet with me to discuss this incident. You are not required to accept this offer. If you would like to meet, please contact me to make an appointment outside of my regular office hours.\r\n\r\nYou may wish to refer to SFU's policies and procedures on academic integrity,\r\n  http://www.sfu.ca/policies/Students/index.html .\r\nYou can also contact the Office of the Ombudsperson for assistance in navigating University procedures.\r\n"},
                 {"field": "facts",
                  "label": "attachment",
                  "text": "See details in attached file facts.pdf."},
                 {"field": "contact_email_text",
                  "label": "simiar work (group)",
                  "text": "You and other students submitted very similar work on {{ACTIVITIES}}. This level of similarity does not usually occur unless collaboration exceeds the limits allowed by SFU's Code of Academic Integrity and Good Conduct, Policy S10.01. I take academic honesty very seriously and intend to pursue this apparent violation of SFU's standards for academic honesty.\r\n\r\nAs required by SFU Policy S10.02, Principles and Procedures for Academic Discipline, I am offering you the opportunity to meet with me to discuss this incident. You are not required to accept this offer. If you would like to meet, please contact me to make an appointment outside of my regular office hours.\r\n\r\nYou may wish to refer to SFU's policies and procedures on academic integrity,\r\n  http://www.sfu.ca/policies/Students/index.html .\r\nYou can also contact the Office of the Ombudsperson for assistance in navigating University procedures.\r\n"},
                 {"field": "facts",
                  "label": "copied (other knew)",
                  "text": "{{FNAME}} was given a solution to {{ACTIVITIES}} by another student. The other student seems to have completed the work independently. Both students submitted the work as their own."},
                 {"field": "facts",
                  "label": "copied (without knowledge)",
                  "text": "{{FNAME}} copied the work of another student on {{ACTIVITIES}} without his/her knowledge.  Both students submitted the work as their own."},
                 {"field": "meeting_summary",
                  "label": "admitted",
                  "text": "The student admitted academic dishonesty as described below in \u201cfacts of the case\u201d."},
                 {"field": "meeting_summary",
                  "label": "quote email",
                  "text": "The student explained the situation in his/her email:\r\n\r\nbq. PASTE QUOTE HERE"},
                 {"field": "meeting_summary",
                  "label": "explained",
                  "text": "{{FNAME}} explained that..."},
                 ]
    for data in templates:
        t = DisciplineTemplate(**data)
        t.save()

    cmpt = Unit.objects.get(slug='cmpt')
    a = Account(account_number=12345, position_number=12345, title='MSc TA', unit=cmpt)
    a.save()
    a = Account(account_number=12346, position_number=12346, title='PhD TA', unit=cmpt)
    a.save()
    a = Account(account_number=12347, position_number=12347, title='External TA', unit=cmpt)
    a.save()
    a = Account(account_number=12348, position_number=12348, title='Undergrad TA', unit=cmpt)
    a.save()

    uc = UserConfig(user=Person.objects.get(userid='dzhao'), key='advisor-token', value={'token': '30378700c0091f34412ec9a082dca267'})
    uc.save()
    uc = UserConfig(user=Person.objects.get(userid='ggbaker'), key='advisor-token', value={'token': '082dca26730378700c0091f34412ec9a'})
    uc.save()
    p = Person(userid='probadmn', emplid='200002387', first_name='Problem', last_name='Admin')
    p.save()
    uc = UserConfig(user=p, key='problems-token', value={'token': '30378700c0091f34412ec9a082dca268'})
    uc.save()

    p = Person(userid='teachadm', emplid='200002388', first_name='Teaching', last_name='Admin')
    p.save()
    r = Role(person=p, role="TADM", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    #sp = SemesterPlan(semester=Semester.objects.get(name=TEST_SEMESTER), name='Test Plan', unit=Unit.objects.get(slug='cmpt'), slug='test-plan')
    #sp.save()
    #o = PlannedOffering(plan=sp, course=Course.objects.get(slug='cmpt-102'), section='D100', campus='BRNBY', enrl_cap=100)
    #o.save()
    #PlanningCourse.create_for_unit(Unit.objects.get(slug='cmpt'))
    #te = TeachingEquivalent(pk=1, instructor=Person.objects.get(userid='ggbaker'), semester=Semester.objects.get(name=TEST_SEMESTER), credits_numerator=1, credits_denominator=1, summary="Foo", status='UNCO')
    #te.save()
    #ti = TeachingIntention(instructor=Person.objects.get(userid='ggbaker'), semester=Semester.objects.get(name=TEST_SEMESTER), count=2)
    #ti.save()
    #tc = TeachingCapability(instructor=Person.objects.get(userid='ggbaker'), course=Course.objects.get(slug='cmpt-102'), note='foo')
    #tc.save()

    p = Person(userid='classam', emplid='200002389', first_name='Curtis', last_name='Lassam')
    p.save()
    r = Role(person=p, role="TECH", unit=Unit.objects.get(slug='cmpt'))
    r.save()
    r = Role(person=p, role="SYSA", unit=Unit.objects.get(slug='cmpt'))
    r.save()

    # create some faculty roles
    members = Member.objects.filter(role='INST', offering__owner__slug='cmpt')
    instr = set(m.person for m in members)
    faculty = random.sample(instr, 10)
    for p in faculty:
        Role.objects.get_or_create(person=p, role='FAC', unit=cmpt)
示例#45
0
    def generate_submission_contents(self, z, prefix='', always_summary=True):
        """
        Assemble submissions and put in ZIP file.
        """
        self.ensure_components()
        assert self.submissions is not None
        assert self.all_submitted_components is not None

        multi = self.activity.multisubmit()

        from submission.models.gittag import GitTagComponent
        any_git_tags = any(
            isinstance(c, GitTagComponent) for c in self.components)
        git_tags = []

        # get SubmittedComponents and metadata
        found, individual_subcomps, last_submission = self.most_recent_submissions(
        )

        # Now add them to the ZIP
        for slug, subcomps in individual_subcomps.items():
            lastsub = last_submission[slug]
            p = os.path.join(prefix, slug)
            self._add_to_zip(z,
                             self.activity,
                             subcomps,
                             lastsub.created_at,
                             slug=lastsub.file_slug(),
                             prefix=p,
                             multi=multi)

            git_tags.extend((comp.slug, slug, sub.url, sub.tag)
                            for comp, sub in subcomps
                            if isinstance(comp, GitTagComponent) and sub)

        # produce summary of submission datetimes
        if found or always_summary:
            slugs = list(last_submission.keys())
            slugs.sort()
            summarybuffer = io.StringIO()
            summarycsv = csv.writer(summarybuffer)
            summarycsv.writerow([Person.userid_header(), "Last Submission"])
            for s in slugs:
                summarycsv.writerow([
                    s,
                    last_submission[s].created_at.strftime("%Y/%m/%d %H:%M:%S")
                ])
            z.writestr(prefix + "summary.csv", summarybuffer.getvalue())
            summarybuffer.close()

        # produce git clone-all script
        if any_git_tags:
            script = [
                '#!/bin/sh', '',
                '# This script will clone all of the submitted git tags for this activity,',
                '# putting them into the current directory. This should work in a Linux, OSX,',
                '# or the Git Bash shell in Windows.', ''
            ]

            git_tags.sort()
            for comp_slug, sub_slug, url, tag in git_tags:
                dir_name = comp_slug + '_' + sub_slug
                script.append(
                    'git clone %s %s && \\\n  (cd %s && git checkout tags/%s)'
                    %
                    (quote(url), quote(dir_name), quote(dir_name), quote(tag)))

            script.append('')
            z.writestr(prefix + "clone-all.sh", '\n'.join(script))
示例#46
0
    def generate_submission_contents(self, z, prefix='', always_summary=True):
        """
        Assemble submissions and put in ZIP file.
        """
        self.ensure_components()
        assert self.submissions is not None
        assert self.all_submitted_components is not None

        multi = self.activity.multisubmit()

        from submission.models.gittag import GitTagComponent
        any_git_tags = any(isinstance(c, GitTagComponent) for c in self.components)
        git_tags = []

        # Collect all of the SubmittedComponents that we need to output
        # i.e. the most recent of each by student|group and component
        found = set()  # (student|group, SubmissionComponent) pairs we have already included
        individual_subcomps = {}  # student|group: [(SubmissionComponent, SubmittedComponent)]
        last_submission = {}  # student|group: final Submission
        for sub, subcomps in self.submissions_and_components():
            slug = sub.file_slug()
            for comp, sc in subcomps:
                key = (slug, comp.slug)
                if (not multi and key in found) or sc is None:
                    continue

                if slug not in last_submission:
                    last_submission[slug] = sub

                found.add(key)

                scs = individual_subcomps.get(slug, [])
                scs.append((comp, sc))

                individual_subcomps[sub.file_slug()] = scs

        # Now add them to the ZIP
        for slug, subcomps in individual_subcomps.items():
            lastsub = last_submission[slug]
            p = os.path.join(prefix, slug)
            self._add_to_zip(z, self.activity, subcomps, lastsub.created_at,
                    slug=lastsub.file_slug(), prefix=p, multi=multi)

            git_tags.extend((comp.slug, slug, sub.url, sub.tag) for comp, sub in subcomps if
                            isinstance(comp, GitTagComponent) and sub)

        # produce summary of submission datetimes
        if found or always_summary:
            slugs = list(last_submission.keys())
            slugs.sort()
            summarybuffer = io.StringIO()
            summarycsv = csv.writer(summarybuffer)
            summarycsv.writerow([Person.userid_header(), "Last Submission"])
            for s in slugs:
                summarycsv.writerow([s, last_submission[s].created_at.strftime("%Y/%m/%d %H:%M:%S")])
            z.writestr(prefix + "summary.csv", summarybuffer.getvalue())
            summarybuffer.close()

        # produce git clone-all script
        if any_git_tags:
            script = ['#!/bin/sh', '', '# This script will clone all of the submitted git tags for this activity,',
                      '# putting them into the current directory. This should work in a Linux, OSX,',
                      '# or the Git Bash shell in Windows.', '']

            git_tags.sort()
            for comp_slug, sub_slug, url, tag in git_tags:
                dir_name = comp_slug + '_' + sub_slug
                script.append('git clone %s %s && \\\n  (cd %s && git checkout tags/%s)' % (
                    quote(url), quote(dir_name), quote(dir_name), quote(tag)))

            script.append('')
            z.writestr(prefix + "clone-all.sh", '\n'.join(script))
示例#47
0
文件: tests.py 项目: avacariu/coursys
 def test_person_2(self):
     p1 = Person(emplid=210012345, userid="test1",
             last_name="Lname", first_name="Fname", pref_first_name="Fn", middle_name="M")
     p1.save()
     px = Person(emplid=210012348, userid="test1")
     self.assertRaises(IntegrityError, px.save)
示例#48
0
def test_class_1(slug):
    """
    main test course: 20 students, TA, some assignments
    """
    crs = CourseOffering.objects.get(slug=slug)
    
    crs.set_labtut(True)
    crs.set_url("http://www.cs.sfu.ca/CC/165/common/")
    crs.set_taemail("*****@*****.**")
    crs.save()
    for i in range(10):
        lab = "D1%02i" % (random.randint(1,4))
        p = Person.objects.get(userid="0aaa%i"%(i))
        if Member.objects.filter(person=p, offering=crs, role="STUD"):
            # randomly added by other student-adder: skip
            continue

        m = Member(person=p, offering=crs, role="STUD", credits=3, career="UGRD", added_reason="AUTO",
                labtut_section=lab)
        m.save()
    
    if not Member.objects.filter(person__userid='ggbaker', offering=crs, role='INST'):
        Member(person=Person.objects.get(userid='ggbaker'), offering=crs, role='INST').save()
    
    # create a TA
    p = Person(emplid=fake_emplid(), userid="0grad1", last_name="Gradstudent", first_name="Douglas", middle_name="", pref_first_name="Doug")
    p.save()
    m = Member(person=p, offering=crs, role="TA", credits=0, career="NONS", added_reason="AUTO",
            labtut_section=None)
    m.save()
    
    
    # create example activities
    crs.activity_set.all().update(deleted=True)
    a1 = NumericActivity(offering=crs, name="Assignment 1", short_name="A1", status="RLS",
        due_date=crs.semester.start + datetime.timedelta(days=60), percent=10, group=False,
        max_grade=10, position=1)
    a1.set_url("http://www.cs.sfu.ca/CC/165/common/a1")
    a1.save()
    a2 = NumericActivity(offering=crs, name="Assignment 2", short_name="A2", status="URLS",
        due_date=crs.semester.start + datetime.timedelta(days=70), percent=10, group=True,
        max_grade=20, position=2)
    a2.save()
    pr = LetterActivity(offering=crs, name="Project", short_name="Proj", status="URLS",
        due_date=crs.semester.start + datetime.timedelta(days=80), percent=40, group=True, position=3)
    pr.save()
    re = LetterActivity(offering=crs, name="Report", short_name="Rep", status="URLS",
        due_date=crs.semester.start + datetime.timedelta(days=81), percent=10, group=False, position=4)
    re.save()
    ex = NumericActivity(offering=crs, name="Final Exam", short_name="Exam", status="URLS",
        due_date=None, percent=30, group=False, max_grade=90, position=5)
    ex.save()
    to = CalNumericActivity(offering=crs, name="Final Percent", short_name="Perc", status="INVI",
        due_date=None, percent=0, group=False, max_grade=100, formula="[[activitytotal]]", position=6)
    to.save()
    to = CalLetterActivity(offering=crs, name="Letter Grade", short_name="Letter", status="INVI",
        due_date=None, percent=0, group=False, numeric_activity=to, position=6)
    to.save()
    
    # make A1 submittable and markable
    s = CodeComponent(activity=a1, title="Code File", description="The code you're submitting.",
        allowed=".py,.java")
    s.save()
    s = PDFComponent(activity=a1, title="Report", description="Report on what you did.",
        specified_filename="report.pdf")
    s.save()
    
    m = ActivityComponent(numeric_activity=a1, max_mark=5, title="Part 1", description="Part 1 was done well and seems to work.", position=1)
    m.save()
    m = ActivityComponent(numeric_activity=a1, max_mark=5, title="Part 2", description="Part 2 was done well and seems to work.", position=2)
    m.save()
    
    # create some groups
    g = Group(name="SomeGroup", courseoffering=crs, manager=Member.objects.get(offering=crs, person__userid="0aaa0", role='STUD'))
    g.save()
    for userid in ['0aaa0', '0aaa1', '0aaa5', '0aaa8']:
        gm = GroupMember(group=g, student=Member.objects.get(offering=crs, person__userid=userid), confirmed=True, activity=a2)
        gm.save()
    
    g = Group(name="AnotherGroup", courseoffering=crs, manager=Member.objects.get(offering=crs, person__userid="0aaa4"))
    g.save()
    for userid in ['0aaa4', '0aaa6', '0aaa7', '0aaa2']:
        gm = GroupMember(group=g, student=Member.objects.get(offering=crs, person__userid=userid), confirmed=True, activity=a2)
        gm.save()
        gm = GroupMember(group=g, student=Member.objects.get(offering=crs, person__userid=userid), confirmed=True, activity=pr)
        gm.save()