Merge lp:~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb into lp:ubuntu/karmic/desktopcouch

Proposed by Chad Miller
Status: Rejected
Rejected by: James Westby
Proposed branch: lp:~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb
Merge into: lp:ubuntu/karmic/desktopcouch
Diff against target: None lines
To merge this branch: bzr merge lp:~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb
Reviewer Review Type Date Requested Status
James Westby (community) Disapprove
Review via email: mp+11778@code.launchpad.net
To post a comment you must log in.
Revision history for this message
James Westby (james-w) wrote :

This should go in after the alpha I think. Pushing it in now
may require a respin, so we only want to do that if it is
critical to have it for the alpha.

Thanks,

James

Revision history for this message
Elliot Murphy (statik) wrote :

> This should go in after the alpha I think. Pushing it in now
> may require a respin, so we only want to do that if it is
> critical to have it for the alpha.

+1 on waiting until after the alpha. I haven't reviewed the branch yet, what might require a respin?

Revision history for this message
James Westby (james-w) wrote :

> > This should go in after the alpha I think. Pushing it in now
> > may require a respin, so we only want to do that if it is
> > critical to have it for the alpha.
>
> +1 on waiting until after the alpha. I haven't reviewed the branch yet, what
> might require a respin?

Getting a new package on the CDs at this point requires a respin of the CDs.

Putting in a new version of the package that is on the CDs and not respinning
is undesirable, as it can lead to headaches if there is a respin, or when
testing.

[ I realise my original comment was ambiguous now. I said "may require
a respin", but meant "may require a respin that isn't going to happen
for other reasons." We could have put the package in as things hadn't
settled down yet, but with all the chaos in the last 24 hours I'm loath
to risk adding to it ]

Thanks,

James

Revision history for this message
James Westby (james-w) wrote :

Hi,

lp:~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb

is not based on lp:ubuntu/desktopcouch, so I can't do the
requested merge.

It is instead based on lp:~ubuntu-desktop/ubuntu/karmic/desktopcouch/karmic
which I could merge to, except I'm not in ~ubuntu-desktop, and
the last upload is not recorded there.

If you would like to continue using the ~ubuntu-desktop branch
then we can accommodate that, and soon make lp:ubuntu/desktopcouch
point to it.

Thanks,

James

review: Disapprove
Revision history for this message
Elliot Murphy (statik) wrote :

On 09/18/2009 06:25 AM, James Westby wrote:
>
> If you would like to continue using the ~ubuntu-desktop branch
> then we can accommodate that, and soon make lp:ubuntu/desktopcouch
> point to it.
>

I wanted to move away from the ~ubuntu-desktop branch since nobody in
ubuntuone-hackers could merge to it. Probably this just needs some
merging to get consistent with the last upload from lp:ubuntu/desktopcouch

--
Elliot Murphy | https://launchpad.net/~statik/

Unmerged revisions

61. By Chad Miller

Merge 0.4.2 from trunk.

60. By Chad Miller

* Log to correct place in service, ~/.cache/desktop-couch/ .
* Abandon service modules giving host and port info separate from the
  db prefixes, which now give a URI.
* Let the replicator gather its own OAuth data to use to connect to far end.
* Make service more resilient to errors, and make breakable parts in smaller
  granules.
* Support Python 2.5.
* Added basic notes record API to include NOTE_RECORD_TYPE.
* Make create-contacts script agnostic of desktop vs cloud and oauth vs noauth.
* New upstream release (LP: #435429)
* Depend on couchdb-bin instead of couchdb (LP: #427036)

59. By Chad Miller

Add replication_services to python-desktopcouch package.

58. By Chad Miller

desktopcouch (0.4-0ubuntu1) karmic; urgency=low

* Packaging: desktopcouch-tools installed by default in Karmic (LP: #427421)
* Forcing desktopcouch auth on. (LP: #427446)
* Requiring new version of couchdb that supports authentication properly.
* Pairing updates couchdb replication system. (LP: #397663)
* Added pairing of desktop Couches to desktopcouch-tools (LP: #404087)
* Admin users in the system couchdb are no longer inherited by desktopcouch
  couchdbs (LP: #424330)
* Fixed failing tests in desktopcouch (LP: #405612)
* Creating login details on initial desktopcouch setup (LP: #416413)
* Starting replication to paired servers on desktopcouch startup.
  (LP: #416581)
* Unpaired couchdb peers are reconciled with replication. (LP: #424386)
* At pairing time, changing couchdb pairing address to public. (LP: #419969)
* In replication daemon, verifying local couchdb bind address is not 127/8 .
  (LP: #419973)
* getPort no longer suceeds when desktopcouch isn't running. (LP: #422127)

 -- Chad Miller <email address hidden>Mon, 14 Sep 2009 19:24:08 -0400

57. By Chad Miller

Merge from desktopcouch trunk for 0.4 release.

56. By Chad Miller

desktopcouch (0.3.1-0ubuntu1) karmic; urgency=low
  - Added depends on python-desktopcouch-records. (LP: #422179)
* New upstream release.
* Fix getPort failure. (LP: #420911, LP: #422127)
* Check couchdb bind-port in replicator. (LP: #419973)
* Change couchdb bind-port in pairing tool. (LP: #419969)

55. By Chad Miller

Release 0.3.1.

54. By Chad Miller

Merge fixes for getPort failures.

53. By Chad Miller

desktopcouch (0.3.1-0ubuntu1) UNRELEASED; urgency=low
[Ken VanDine]
* debian/control
[Chad Miller]
* Changed Vcs-Bzr links in control file.
* Changed version dependency on couchdb.
* Converting to a full-blown source-package branch.
 -- Chad Miller <email address hidden>Tue, 01 Sep 2009 11:57:25 -0400

52. By Chad Miller

Taking over packaging branch from
lp:~ubuntu-desktop/ubuntu/karmic/desktopcouch/karmic at revno:82,
revid:<email address hidden>

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added file 'COPYING'
2--- COPYING 1970-01-01 00:00:00 +0000
3+++ COPYING 2009-07-09 20:17:15 +0000
4@@ -0,0 +1,676 @@
5+
6+ GNU GENERAL PUBLIC LICENSE
7+ Version 3, 29 June 2007
8+
9+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
10+ Everyone is permitted to copy and distribute verbatim copies
11+ of this license document, but changing it is not allowed.
12+
13+ Preamble
14+
15+ The GNU General Public License is a free, copyleft license for
16+software and other kinds of works.
17+
18+ The licenses for most software and other practical works are designed
19+to take away your freedom to share and change the works. By contrast,
20+the GNU General Public License is intended to guarantee your freedom to
21+share and change all versions of a program--to make sure it remains free
22+software for all its users. We, the Free Software Foundation, use the
23+GNU General Public License for most of our software; it applies also to
24+any other work released this way by its authors. You can apply it to
25+your programs, too.
26+
27+ When we speak of free software, we are referring to freedom, not
28+price. Our General Public Licenses are designed to make sure that you
29+have the freedom to distribute copies of free software (and charge for
30+them if you wish), that you receive source code or can get it if you
31+want it, that you can change the software or use pieces of it in new
32+free programs, and that you know you can do these things.
33+
34+ To protect your rights, we need to prevent others from denying you
35+these rights or asking you to surrender the rights. Therefore, you have
36+certain responsibilities if you distribute copies of the software, or if
37+you modify it: responsibilities to respect the freedom of others.
38+
39+ For example, if you distribute copies of such a program, whether
40+gratis or for a fee, you must pass on to the recipients the same
41+freedoms that you received. You must make sure that they, too, receive
42+or can get the source code. And you must show them these terms so they
43+know their rights.
44+
45+ Developers that use the GNU GPL protect your rights with two steps:
46+(1) assert copyright on the software, and (2) offer you this License
47+giving you legal permission to copy, distribute and/or modify it.
48+
49+ For the developers' and authors' protection, the GPL clearly explains
50+that there is no warranty for this free software. For both users' and
51+authors' sake, the GPL requires that modified versions be marked as
52+changed, so that their problems will not be attributed erroneously to
53+authors of previous versions.
54+
55+ Some devices are designed to deny users access to install or run
56+modified versions of the software inside them, although the manufacturer
57+can do so. This is fundamentally incompatible with the aim of
58+protecting users' freedom to change the software. The systematic
59+pattern of such abuse occurs in the area of products for individuals to
60+use, which is precisely where it is most unacceptable. Therefore, we
61+have designed this version of the GPL to prohibit the practice for those
62+products. If such problems arise substantially in other domains, we
63+stand ready to extend this provision to those domains in future versions
64+of the GPL, as needed to protect the freedom of users.
65+
66+ Finally, every program is threatened constantly by software patents.
67+States should not allow patents to restrict development and use of
68+software on general-purpose computers, but in those that do, we wish to
69+avoid the special danger that patents applied to a free program could
70+make it effectively proprietary. To prevent this, the GPL assures that
71+patents cannot be used to render the program non-free.
72+
73+ The precise terms and conditions for copying, distribution and
74+modification follow.
75+
76+ TERMS AND CONDITIONS
77+
78+ 0. Definitions.
79+
80+ "This License" refers to version 3 of the GNU General Public License.
81+
82+ "Copyright" also means copyright-like laws that apply to other kinds of
83+works, such as semiconductor masks.
84+
85+ "The Program" refers to any copyrightable work licensed under this
86+License. Each licensee is addressed as "you". "Licensees" and
87+"recipients" may be individuals or organizations.
88+
89+ To "modify" a work means to copy from or adapt all or part of the work
90+in a fashion requiring copyright permission, other than the making of an
91+exact copy. The resulting work is called a "modified version" of the
92+earlier work or a work "based on" the earlier work.
93+
94+ A "covered work" means either the unmodified Program or a work based
95+on the Program.
96+
97+ To "propagate" a work means to do anything with it that, without
98+permission, would make you directly or secondarily liable for
99+infringement under applicable copyright law, except executing it on a
100+computer or modifying a private copy. Propagation includes copying,
101+distribution (with or without modification), making available to the
102+public, and in some countries other activities as well.
103+
104+ To "convey" a work means any kind of propagation that enables other
105+parties to make or receive copies. Mere interaction with a user through
106+a computer network, with no transfer of a copy, is not conveying.
107+
108+ An interactive user interface displays "Appropriate Legal Notices"
109+to the extent that it includes a convenient and prominently visible
110+feature that (1) displays an appropriate copyright notice, and (2)
111+tells the user that there is no warranty for the work (except to the
112+extent that warranties are provided), that licensees may convey the
113+work under this License, and how to view a copy of this License. If
114+the interface presents a list of user commands or options, such as a
115+menu, a prominent item in the list meets this criterion.
116+
117+ 1. Source Code.
118+
119+ The "source code" for a work means the preferred form of the work
120+for making modifications to it. "Object code" means any non-source
121+form of a work.
122+
123+ A "Standard Interface" means an interface that either is an official
124+standard defined by a recognized standards body, or, in the case of
125+interfaces specified for a particular programming language, one that
126+is widely used among developers working in that language.
127+
128+ The "System Libraries" of an executable work include anything, other
129+than the work as a whole, that (a) is included in the normal form of
130+packaging a Major Component, but which is not part of that Major
131+Component, and (b) serves only to enable use of the work with that
132+Major Component, or to implement a Standard Interface for which an
133+implementation is available to the public in source code form. A
134+"Major Component", in this context, means a major essential component
135+(kernel, window system, and so on) of the specific operating system
136+(if any) on which the executable work runs, or a compiler used to
137+produce the work, or an object code interpreter used to run it.
138+
139+ The "Corresponding Source" for a work in object code form means all
140+the source code needed to generate, install, and (for an executable
141+work) run the object code and to modify the work, including scripts to
142+control those activities. However, it does not include the work's
143+System Libraries, or general-purpose tools or generally available free
144+programs which are used unmodified in performing those activities but
145+which are not part of the work. For example, Corresponding Source
146+includes interface definition files associated with source files for
147+the work, and the source code for shared libraries and dynamically
148+linked subprograms that the work is specifically designed to require,
149+such as by intimate data communication or control flow between those
150+subprograms and other parts of the work.
151+
152+ The Corresponding Source need not include anything that users
153+can regenerate automatically from other parts of the Corresponding
154+Source.
155+
156+ The Corresponding Source for a work in source code form is that
157+same work.
158+
159+ 2. Basic Permissions.
160+
161+ All rights granted under this License are granted for the term of
162+copyright on the Program, and are irrevocable provided the stated
163+conditions are met. This License explicitly affirms your unlimited
164+permission to run the unmodified Program. The output from running a
165+covered work is covered by this License only if the output, given its
166+content, constitutes a covered work. This License acknowledges your
167+rights of fair use or other equivalent, as provided by copyright law.
168+
169+ You may make, run and propagate covered works that you do not
170+convey, without conditions so long as your license otherwise remains
171+in force. You may convey covered works to others for the sole purpose
172+of having them make modifications exclusively for you, or provide you
173+with facilities for running those works, provided that you comply with
174+the terms of this License in conveying all material for which you do
175+not control copyright. Those thus making or running the covered works
176+for you must do so exclusively on your behalf, under your direction
177+and control, on terms that prohibit them from making any copies of
178+your copyrighted material outside their relationship with you.
179+
180+ Conveying under any other circumstances is permitted solely under
181+the conditions stated below. Sublicensing is not allowed; section 10
182+makes it unnecessary.
183+
184+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
185+
186+ No covered work shall be deemed part of an effective technological
187+measure under any applicable law fulfilling obligations under article
188+11 of the WIPO copyright treaty adopted on 20 December 1996, or
189+similar laws prohibiting or restricting circumvention of such
190+measures.
191+
192+ When you convey a covered work, you waive any legal power to forbid
193+circumvention of technological measures to the extent such circumvention
194+is effected by exercising rights under this License with respect to
195+the covered work, and you disclaim any intention to limit operation or
196+modification of the work as a means of enforcing, against the work's
197+users, your or third parties' legal rights to forbid circumvention of
198+technological measures.
199+
200+ 4. Conveying Verbatim Copies.
201+
202+ You may convey verbatim copies of the Program's source code as you
203+receive it, in any medium, provided that you conspicuously and
204+appropriately publish on each copy an appropriate copyright notice;
205+keep intact all notices stating that this License and any
206+non-permissive terms added in accord with section 7 apply to the code;
207+keep intact all notices of the absence of any warranty; and give all
208+recipients a copy of this License along with the Program.
209+
210+ You may charge any price or no price for each copy that you convey,
211+and you may offer support or warranty protection for a fee.
212+
213+ 5. Conveying Modified Source Versions.
214+
215+ You may convey a work based on the Program, or the modifications to
216+produce it from the Program, in the form of source code under the
217+terms of section 4, provided that you also meet all of these conditions:
218+
219+ a) The work must carry prominent notices stating that you modified
220+ it, and giving a relevant date.
221+
222+ b) The work must carry prominent notices stating that it is
223+ released under this License and any conditions added under section
224+ 7. This requirement modifies the requirement in section 4 to
225+ "keep intact all notices".
226+
227+ c) You must license the entire work, as a whole, under this
228+ License to anyone who comes into possession of a copy. This
229+ License will therefore apply, along with any applicable section 7
230+ additional terms, to the whole of the work, and all its parts,
231+ regardless of how they are packaged. This License gives no
232+ permission to license the work in any other way, but it does not
233+ invalidate such permission if you have separately received it.
234+
235+ d) If the work has interactive user interfaces, each must display
236+ Appropriate Legal Notices; however, if the Program has interactive
237+ interfaces that do not display Appropriate Legal Notices, your
238+ work need not make them do so.
239+
240+ A compilation of a covered work with other separate and independent
241+works, which are not by their nature extensions of the covered work,
242+and which are not combined with it such as to form a larger program,
243+in or on a volume of a storage or distribution medium, is called an
244+"aggregate" if the compilation and its resulting copyright are not
245+used to limit the access or legal rights of the compilation's users
246+beyond what the individual works permit. Inclusion of a covered work
247+in an aggregate does not cause this License to apply to the other
248+parts of the aggregate.
249+
250+ 6. Conveying Non-Source Forms.
251+
252+ You may convey a covered work in object code form under the terms
253+of sections 4 and 5, provided that you also convey the
254+machine-readable Corresponding Source under the terms of this License,
255+in one of these ways:
256+
257+ a) Convey the object code in, or embodied in, a physical product
258+ (including a physical distribution medium), accompanied by the
259+ Corresponding Source fixed on a durable physical medium
260+ customarily used for software interchange.
261+
262+ b) Convey the object code in, or embodied in, a physical product
263+ (including a physical distribution medium), accompanied by a
264+ written offer, valid for at least three years and valid for as
265+ long as you offer spare parts or customer support for that product
266+ model, to give anyone who possesses the object code either (1) a
267+ copy of the Corresponding Source for all the software in the
268+ product that is covered by this License, on a durable physical
269+ medium customarily used for software interchange, for a price no
270+ more than your reasonable cost of physically performing this
271+ conveying of source, or (2) access to copy the
272+ Corresponding Source from a network server at no charge.
273+
274+ c) Convey individual copies of the object code with a copy of the
275+ written offer to provide the Corresponding Source. This
276+ alternative is allowed only occasionally and noncommercially, and
277+ only if you received the object code with such an offer, in accord
278+ with subsection 6b.
279+
280+ d) Convey the object code by offering access from a designated
281+ place (gratis or for a charge), and offer equivalent access to the
282+ Corresponding Source in the same way through the same place at no
283+ further charge. You need not require recipients to copy the
284+ Corresponding Source along with the object code. If the place to
285+ copy the object code is a network server, the Corresponding Source
286+ may be on a different server (operated by you or a third party)
287+ that supports equivalent copying facilities, provided you maintain
288+ clear directions next to the object code saying where to find the
289+ Corresponding Source. Regardless of what server hosts the
290+ Corresponding Source, you remain obligated to ensure that it is
291+ available for as long as needed to satisfy these requirements.
292+
293+ e) Convey the object code using peer-to-peer transmission, provided
294+ you inform other peers where the object code and Corresponding
295+ Source of the work are being offered to the general public at no
296+ charge under subsection 6d.
297+
298+ A separable portion of the object code, whose source code is excluded
299+from the Corresponding Source as a System Library, need not be
300+included in conveying the object code work.
301+
302+ A "User Product" is either (1) a "consumer product", which means any
303+tangible personal property which is normally used for personal, family,
304+or household purposes, or (2) anything designed or sold for incorporation
305+into a dwelling. In determining whether a product is a consumer product,
306+doubtful cases shall be resolved in favor of coverage. For a particular
307+product received by a particular user, "normally used" refers to a
308+typical or common use of that class of product, regardless of the status
309+of the particular user or of the way in which the particular user
310+actually uses, or expects or is expected to use, the product. A product
311+is a consumer product regardless of whether the product has substantial
312+commercial, industrial or non-consumer uses, unless such uses represent
313+the only significant mode of use of the product.
314+
315+ "Installation Information" for a User Product means any methods,
316+procedures, authorization keys, or other information required to install
317+and execute modified versions of a covered work in that User Product from
318+a modified version of its Corresponding Source. The information must
319+suffice to ensure that the continued functioning of the modified object
320+code is in no case prevented or interfered with solely because
321+modification has been made.
322+
323+ If you convey an object code work under this section in, or with, or
324+specifically for use in, a User Product, and the conveying occurs as
325+part of a transaction in which the right of possession and use of the
326+User Product is transferred to the recipient in perpetuity or for a
327+fixed term (regardless of how the transaction is characterized), the
328+Corresponding Source conveyed under this section must be accompanied
329+by the Installation Information. But this requirement does not apply
330+if neither you nor any third party retains the ability to install
331+modified object code on the User Product (for example, the work has
332+been installed in ROM).
333+
334+ The requirement to provide Installation Information does not include a
335+requirement to continue to provide support service, warranty, or updates
336+for a work that has been modified or installed by the recipient, or for
337+the User Product in which it has been modified or installed. Access to a
338+network may be denied when the modification itself materially and
339+adversely affects the operation of the network or violates the rules and
340+protocols for communication across the network.
341+
342+ Corresponding Source conveyed, and Installation Information provided,
343+in accord with this section must be in a format that is publicly
344+documented (and with an implementation available to the public in
345+source code form), and must require no special password or key for
346+unpacking, reading or copying.
347+
348+ 7. Additional Terms.
349+
350+ "Additional permissions" are terms that supplement the terms of this
351+License by making exceptions from one or more of its conditions.
352+Additional permissions that are applicable to the entire Program shall
353+be treated as though they were included in this License, to the extent
354+that they are valid under applicable law. If additional permissions
355+apply only to part of the Program, that part may be used separately
356+under those permissions, but the entire Program remains governed by
357+this License without regard to the additional permissions.
358+
359+ When you convey a copy of a covered work, you may at your option
360+remove any additional permissions from that copy, or from any part of
361+it. (Additional permissions may be written to require their own
362+removal in certain cases when you modify the work.) You may place
363+additional permissions on material, added by you to a covered work,
364+for which you have or can give appropriate copyright permission.
365+
366+ Notwithstanding any other provision of this License, for material you
367+add to a covered work, you may (if authorized by the copyright holders of
368+that material) supplement the terms of this License with terms:
369+
370+ a) Disclaiming warranty or limiting liability differently from the
371+ terms of sections 15 and 16 of this License; or
372+
373+ b) Requiring preservation of specified reasonable legal notices or
374+ author attributions in that material or in the Appropriate Legal
375+ Notices displayed by works containing it; or
376+
377+ c) Prohibiting misrepresentation of the origin of that material, or
378+ requiring that modified versions of such material be marked in
379+ reasonable ways as different from the original version; or
380+
381+ d) Limiting the use for publicity purposes of names of licensors or
382+ authors of the material; or
383+
384+ e) Declining to grant rights under trademark law for use of some
385+ trade names, trademarks, or service marks; or
386+
387+ f) Requiring indemnification of licensors and authors of that
388+ material by anyone who conveys the material (or modified versions of
389+ it) with contractual assumptions of liability to the recipient, for
390+ any liability that these contractual assumptions directly impose on
391+ those licensors and authors.
392+
393+ All other non-permissive additional terms are considered "further
394+restrictions" within the meaning of section 10. If the Program as you
395+received it, or any part of it, contains a notice stating that it is
396+governed by this License along with a term that is a further
397+restriction, you may remove that term. If a license document contains
398+a further restriction but permits relicensing or conveying under this
399+License, you may add to a covered work material governed by the terms
400+of that license document, provided that the further restriction does
401+not survive such relicensing or conveying.
402+
403+ If you add terms to a covered work in accord with this section, you
404+must place, in the relevant source files, a statement of the
405+additional terms that apply to those files, or a notice indicating
406+where to find the applicable terms.
407+
408+ Additional terms, permissive or non-permissive, may be stated in the
409+form of a separately written license, or stated as exceptions;
410+the above requirements apply either way.
411+
412+ 8. Termination.
413+
414+ You may not propagate or modify a covered work except as expressly
415+provided under this License. Any attempt otherwise to propagate or
416+modify it is void, and will automatically terminate your rights under
417+this License (including any patent licenses granted under the third
418+paragraph of section 11).
419+
420+ However, if you cease all violation of this License, then your
421+license from a particular copyright holder is reinstated (a)
422+provisionally, unless and until the copyright holder explicitly and
423+finally terminates your license, and (b) permanently, if the copyright
424+holder fails to notify you of the violation by some reasonable means
425+prior to 60 days after the cessation.
426+
427+ Moreover, your license from a particular copyright holder is
428+reinstated permanently if the copyright holder notifies you of the
429+violation by some reasonable means, this is the first time you have
430+received notice of violation of this License (for any work) from that
431+copyright holder, and you cure the violation prior to 30 days after
432+your receipt of the notice.
433+
434+ Termination of your rights under this section does not terminate the
435+licenses of parties who have received copies or rights from you under
436+this License. If your rights have been terminated and not permanently
437+reinstated, you do not qualify to receive new licenses for the same
438+material under section 10.
439+
440+ 9. Acceptance Not Required for Having Copies.
441+
442+ You are not required to accept this License in order to receive or
443+run a copy of the Program. Ancillary propagation of a covered work
444+occurring solely as a consequence of using peer-to-peer transmission
445+to receive a copy likewise does not require acceptance. However,
446+nothing other than this License grants you permission to propagate or
447+modify any covered work. These actions infringe copyright if you do
448+not accept this License. Therefore, by modifying or propagating a
449+covered work, you indicate your acceptance of this License to do so.
450+
451+ 10. Automatic Licensing of Downstream Recipients.
452+
453+ Each time you convey a covered work, the recipient automatically
454+receives a license from the original licensors, to run, modify and
455+propagate that work, subject to this License. You are not responsible
456+for enforcing compliance by third parties with this License.
457+
458+ An "entity transaction" is a transaction transferring control of an
459+organization, or substantially all assets of one, or subdividing an
460+organization, or merging organizations. If propagation of a covered
461+work results from an entity transaction, each party to that
462+transaction who receives a copy of the work also receives whatever
463+licenses to the work the party's predecessor in interest had or could
464+give under the previous paragraph, plus a right to possession of the
465+Corresponding Source of the work from the predecessor in interest, if
466+the predecessor has it or can get it with reasonable efforts.
467+
468+ You may not impose any further restrictions on the exercise of the
469+rights granted or affirmed under this License. For example, you may
470+not impose a license fee, royalty, or other charge for exercise of
471+rights granted under this License, and you may not initiate litigation
472+(including a cross-claim or counterclaim in a lawsuit) alleging that
473+any patent claim is infringed by making, using, selling, offering for
474+sale, or importing the Program or any portion of it.
475+
476+ 11. Patents.
477+
478+ A "contributor" is a copyright holder who authorizes use under this
479+License of the Program or a work on which the Program is based. The
480+work thus licensed is called the contributor's "contributor version".
481+
482+ A contributor's "essential patent claims" are all patent claims
483+owned or controlled by the contributor, whether already acquired or
484+hereafter acquired, that would be infringed by some manner, permitted
485+by this License, of making, using, or selling its contributor version,
486+but do not include claims that would be infringed only as a
487+consequence of further modification of the contributor version. For
488+purposes of this definition, "control" includes the right to grant
489+patent sublicenses in a manner consistent with the requirements of
490+this License.
491+
492+ Each contributor grants you a non-exclusive, worldwide, royalty-free
493+patent license under the contributor's essential patent claims, to
494+make, use, sell, offer for sale, import and otherwise run, modify and
495+propagate the contents of its contributor version.
496+
497+ In the following three paragraphs, a "patent license" is any express
498+agreement or commitment, however denominated, not to enforce a patent
499+(such as an express permission to practice a patent or covenant not to
500+sue for patent infringement). To "grant" such a patent license to a
501+party means to make such an agreement or commitment not to enforce a
502+patent against the party.
503+
504+ If you convey a covered work, knowingly relying on a patent license,
505+and the Corresponding Source of the work is not available for anyone
506+to copy, free of charge and under the terms of this License, through a
507+publicly available network server or other readily accessible means,
508+then you must either (1) cause the Corresponding Source to be so
509+available, or (2) arrange to deprive yourself of the benefit of the
510+patent license for this particular work, or (3) arrange, in a manner
511+consistent with the requirements of this License, to extend the patent
512+license to downstream recipients. "Knowingly relying" means you have
513+actual knowledge that, but for the patent license, your conveying the
514+covered work in a country, or your recipient's use of the covered work
515+in a country, would infringe one or more identifiable patents in that
516+country that you have reason to believe are valid.
517+
518+ If, pursuant to or in connection with a single transaction or
519+arrangement, you convey, or propagate by procuring conveyance of, a
520+covered work, and grant a patent license to some of the parties
521+receiving the covered work authorizing them to use, propagate, modify
522+or convey a specific copy of the covered work, then the patent license
523+you grant is automatically extended to all recipients of the covered
524+work and works based on it.
525+
526+ A patent license is "discriminatory" if it does not include within
527+the scope of its coverage, prohibits the exercise of, or is
528+conditioned on the non-exercise of one or more of the rights that are
529+specifically granted under this License. You may not convey a covered
530+work if you are a party to an arrangement with a third party that is
531+in the business of distributing software, under which you make payment
532+to the third party based on the extent of your activity of conveying
533+the work, and under which the third party grants, to any of the
534+parties who would receive the covered work from you, a discriminatory
535+patent license (a) in connection with copies of the covered work
536+conveyed by you (or copies made from those copies), or (b) primarily
537+for and in connection with specific products or compilations that
538+contain the covered work, unless you entered into that arrangement,
539+or that patent license was granted, prior to 28 March 2007.
540+
541+ Nothing in this License shall be construed as excluding or limiting
542+any implied license or other defenses to infringement that may
543+otherwise be available to you under applicable patent law.
544+
545+ 12. No Surrender of Others' Freedom.
546+
547+ If conditions are imposed on you (whether by court order, agreement or
548+otherwise) that contradict the conditions of this License, they do not
549+excuse you from the conditions of this License. If you cannot convey a
550+covered work so as to satisfy simultaneously your obligations under this
551+License and any other pertinent obligations, then as a consequence you may
552+not convey it at all. For example, if you agree to terms that obligate you
553+to collect a royalty for further conveying from those to whom you convey
554+the Program, the only way you could satisfy both those terms and this
555+License would be to refrain entirely from conveying the Program.
556+
557+ 13. Use with the GNU Affero General Public License.
558+
559+ Notwithstanding any other provision of this License, you have
560+permission to link or combine any covered work with a work licensed
561+under version 3 of the GNU Affero General Public License into a single
562+combined work, and to convey the resulting work. The terms of this
563+License will continue to apply to the part which is the covered work,
564+but the special requirements of the GNU Affero General Public License,
565+section 13, concerning interaction through a network will apply to the
566+combination as such.
567+
568+ 14. Revised Versions of this License.
569+
570+ The Free Software Foundation may publish revised and/or new versions of
571+the GNU General Public License from time to time. Such new versions will
572+be similar in spirit to the present version, but may differ in detail to
573+address new problems or concerns.
574+
575+ Each version is given a distinguishing version number. If the
576+Program specifies that a certain numbered version of the GNU General
577+Public License "or any later version" applies to it, you have the
578+option of following the terms and conditions either of that numbered
579+version or of any later version published by the Free Software
580+Foundation. If the Program does not specify a version number of the
581+GNU General Public License, you may choose any version ever published
582+by the Free Software Foundation.
583+
584+ If the Program specifies that a proxy can decide which future
585+versions of the GNU General Public License can be used, that proxy's
586+public statement of acceptance of a version permanently authorizes you
587+to choose that version for the Program.
588+
589+ Later license versions may give you additional or different
590+permissions. However, no additional obligations are imposed on any
591+author or copyright holder as a result of your choosing to follow a
592+later version.
593+
594+ 15. Disclaimer of Warranty.
595+
596+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
597+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
598+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
599+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
600+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
601+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
602+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
603+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
604+
605+ 16. Limitation of Liability.
606+
607+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
608+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
609+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
610+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
611+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
612+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
613+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
614+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
615+SUCH DAMAGES.
616+
617+ 17. Interpretation of Sections 15 and 16.
618+
619+ If the disclaimer of warranty and limitation of liability provided
620+above cannot be given local legal effect according to their terms,
621+reviewing courts shall apply local law that most closely approximates
622+an absolute waiver of all civil liability in connection with the
623+Program, unless a warranty or assumption of liability accompanies a
624+copy of the Program in return for a fee.
625+
626+ END OF TERMS AND CONDITIONS
627+
628+ How to Apply These Terms to Your New Programs
629+
630+ If you develop a new program, and you want it to be of the greatest
631+possible use to the public, the best way to achieve this is to make it
632+free software which everyone can redistribute and change under these terms.
633+
634+ To do so, attach the following notices to the program. It is safest
635+to attach them to the start of each source file to most effectively
636+state the exclusion of warranty; and each file should have at least
637+the "copyright" line and a pointer to where the full notice is found.
638+
639+ <one line to give the program's name and a brief idea of what it does.>
640+ Copyright (C) <year> <name of author>
641+
642+ This program is free software: you can redistribute it and/or modify
643+ it under the terms of the GNU General Public License as published by
644+ the Free Software Foundation, either version 3 of the License, or
645+ (at your option) any later version.
646+
647+ This program is distributed in the hope that it will be useful,
648+ but WITHOUT ANY WARRANTY; without even the implied warranty of
649+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
650+ GNU General Public License for more details.
651+
652+ You should have received a copy of the GNU General Public License
653+ along with this program. If not, see <http://www.gnu.org/licenses/>.
654+
655+Also add information on how to contact you by electronic and paper mail.
656+
657+ If the program does terminal interaction, make it output a short
658+notice like this when it starts in an interactive mode:
659+
660+ <program> Copyright (C) <year> <name of author>
661+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
662+ This is free software, and you are welcome to redistribute it
663+ under certain conditions; type `show c' for details.
664+
665+The hypothetical commands `show w' and `show c' should show the appropriate
666+parts of the General Public License. Of course, your program's commands
667+might be different; for a GUI interface, you would use an "about box".
668+
669+ You should also get your employer (if you work as a programmer) or school,
670+if any, to sign a "copyright disclaimer" for the program, if necessary.
671+For more information on this, and how to apply and follow the GNU GPL, see
672+<http://www.gnu.org/licenses/>.
673+
674+ The GNU General Public License does not permit incorporating your program
675+into proprietary programs. If your program is a subroutine library, you
676+may consider it more useful to permit linking proprietary applications with
677+the library. If this is what you want to do, use the GNU Lesser General
678+Public License instead of this License. But first, please read
679+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
680+
681
682=== added file 'COPYING.LESSER'
683--- COPYING.LESSER 1970-01-01 00:00:00 +0000
684+++ COPYING.LESSER 2009-07-13 15:53:45 +0000
685@@ -0,0 +1,165 @@
686+ GNU LESSER GENERAL PUBLIC LICENSE
687+ Version 3, 29 June 2007
688+
689+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
690+ Everyone is permitted to copy and distribute verbatim copies
691+ of this license document, but changing it is not allowed.
692+
693+
694+ This version of the GNU Lesser General Public License incorporates
695+the terms and conditions of version 3 of the GNU General Public
696+License, supplemented by the additional permissions listed below.
697+
698+ 0. Additional Definitions.
699+
700+ As used herein, "this License" refers to version 3 of the GNU Lesser
701+General Public License, and the "GNU GPL" refers to version 3 of the GNU
702+General Public License.
703+
704+ "The Library" refers to a covered work governed by this License,
705+other than an Application or a Combined Work as defined below.
706+
707+ An "Application" is any work that makes use of an interface provided
708+by the Library, but which is not otherwise based on the Library.
709+Defining a subclass of a class defined by the Library is deemed a mode
710+of using an interface provided by the Library.
711+
712+ A "Combined Work" is a work produced by combining or linking an
713+Application with the Library. The particular version of the Library
714+with which the Combined Work was made is also called the "Linked
715+Version".
716+
717+ The "Minimal Corresponding Source" for a Combined Work means the
718+Corresponding Source for the Combined Work, excluding any source code
719+for portions of the Combined Work that, considered in isolation, are
720+based on the Application, and not on the Linked Version.
721+
722+ The "Corresponding Application Code" for a Combined Work means the
723+object code and/or source code for the Application, including any data
724+and utility programs needed for reproducing the Combined Work from the
725+Application, but excluding the System Libraries of the Combined Work.
726+
727+ 1. Exception to Section 3 of the GNU GPL.
728+
729+ You may convey a covered work under sections 3 and 4 of this License
730+without being bound by section 3 of the GNU GPL.
731+
732+ 2. Conveying Modified Versions.
733+
734+ If you modify a copy of the Library, and, in your modifications, a
735+facility refers to a function or data to be supplied by an Application
736+that uses the facility (other than as an argument passed when the
737+facility is invoked), then you may convey a copy of the modified
738+version:
739+
740+ a) under this License, provided that you make a good faith effort to
741+ ensure that, in the event an Application does not supply the
742+ function or data, the facility still operates, and performs
743+ whatever part of its purpose remains meaningful, or
744+
745+ b) under the GNU GPL, with none of the additional permissions of
746+ this License applicable to that copy.
747+
748+ 3. Object Code Incorporating Material from Library Header Files.
749+
750+ The object code form of an Application may incorporate material from
751+a header file that is part of the Library. You may convey such object
752+code under terms of your choice, provided that, if the incorporated
753+material is not limited to numerical parameters, data structure
754+layouts and accessors, or small macros, inline functions and templates
755+(ten or fewer lines in length), you do both of the following:
756+
757+ a) Give prominent notice with each copy of the object code that the
758+ Library is used in it and that the Library and its use are
759+ covered by this License.
760+
761+ b) Accompany the object code with a copy of the GNU GPL and this license
762+ document.
763+
764+ 4. Combined Works.
765+
766+ You may convey a Combined Work under terms of your choice that,
767+taken together, effectively do not restrict modification of the
768+portions of the Library contained in the Combined Work and reverse
769+engineering for debugging such modifications, if you also do each of
770+the following:
771+
772+ a) Give prominent notice with each copy of the Combined Work that
773+ the Library is used in it and that the Library and its use are
774+ covered by this License.
775+
776+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
777+ document.
778+
779+ c) For a Combined Work that displays copyright notices during
780+ execution, include the copyright notice for the Library among
781+ these notices, as well as a reference directing the user to the
782+ copies of the GNU GPL and this license document.
783+
784+ d) Do one of the following:
785+
786+ 0) Convey the Minimal Corresponding Source under the terms of this
787+ License, and the Corresponding Application Code in a form
788+ suitable for, and under terms that permit, the user to
789+ recombine or relink the Application with a modified version of
790+ the Linked Version to produce a modified Combined Work, in the
791+ manner specified by section 6 of the GNU GPL for conveying
792+ Corresponding Source.
793+
794+ 1) Use a suitable shared library mechanism for linking with the
795+ Library. A suitable mechanism is one that (a) uses at run time
796+ a copy of the Library already present on the user's computer
797+ system, and (b) will operate properly with a modified version
798+ of the Library that is interface-compatible with the Linked
799+ Version.
800+
801+ e) Provide Installation Information, but only if you would otherwise
802+ be required to provide such information under section 6 of the
803+ GNU GPL, and only to the extent that such information is
804+ necessary to install and execute a modified version of the
805+ Combined Work produced by recombining or relinking the
806+ Application with a modified version of the Linked Version. (If
807+ you use option 4d0, the Installation Information must accompany
808+ the Minimal Corresponding Source and Corresponding Application
809+ Code. If you use option 4d1, you must provide the Installation
810+ Information in the manner specified by section 6 of the GNU GPL
811+ for conveying Corresponding Source.)
812+
813+ 5. Combined Libraries.
814+
815+ You may place library facilities that are a work based on the
816+Library side by side in a single library together with other library
817+facilities that are not Applications and are not covered by this
818+License, and convey such a combined library under terms of your
819+choice, if you do both of the following:
820+
821+ a) Accompany the combined library with a copy of the same work based
822+ on the Library, uncombined with any other library facilities,
823+ conveyed under the terms of this License.
824+
825+ b) Give prominent notice with the combined library that part of it
826+ is a work based on the Library, and explaining where to find the
827+ accompanying uncombined form of the same work.
828+
829+ 6. Revised Versions of the GNU Lesser General Public License.
830+
831+ The Free Software Foundation may publish revised and/or new versions
832+of the GNU Lesser General Public License from time to time. Such new
833+versions will be similar in spirit to the present version, but may
834+differ in detail to address new problems or concerns.
835+
836+ Each version is given a distinguishing version number. If the
837+Library as you received it specifies that a certain numbered version
838+of the GNU Lesser General Public License "or any later version"
839+applies to it, you have the option of following the terms and
840+conditions either of that published version or of any later version
841+published by the Free Software Foundation. If the Library as you
842+received it does not specify a version number of the GNU Lesser
843+General Public License, you may choose any version of the GNU Lesser
844+General Public License ever published by the Free Software Foundation.
845+
846+ If the Library as you received it specifies that a proxy can decide
847+whether future versions of the GNU Lesser General Public License shall
848+apply, that proxy's public statement of acceptance of any version is
849+permanent authorization for you to choose that version for the
850+Library.
851
852=== added file 'MANIFEST.in'
853--- MANIFEST.in 1970-01-01 00:00:00 +0000
854+++ MANIFEST.in 2009-09-11 19:08:53 +0000
855@@ -0,0 +1,14 @@
856+include COPYING COPYING.LESSER README
857+recursive-include data *.tmpl
858+include desktopcouch-pair.desktop.in
859+include po/POTFILES.in
860+include start-desktop-couchdb.sh
861+include stop-desktop-couchdb.sh
862+include desktopcouch/records/doc/records.txt
863+include bin/*
864+include docs/man/*
865+include MANIFEST.in MANIFEST
866+include org.desktopcouch.CouchDB.service
867+include config/desktop-couch/compulsory-auth.ini
868+recursive-include contrib *.py
869+
870
871=== added file 'README'
872--- README 1970-01-01 00:00:00 +0000
873+++ README 2009-08-07 12:43:11 +0000
874@@ -0,0 +1,35 @@
875+This is Desktop Couch, an infrastructure to place a CouchDB on every desktop
876+and provide APIs and management tools for applications to store data within
877+it and share that data between computers and to the cloud.
878+
879+= Technical notes =
880+
881+== Creating databases, design documents, and views ==
882+
883+Desktop Couch will automatically create databases and design documents for you
884+on startup by inspecting the filesystem, meaning that you do not need to check
885+in your application whether your views exist. It is of course possible to create
886+views directly through the Records API, but having them created via the
887+filesystem allows managing of the view definitions more easily (they are
888+in separately editable files, which helps with version control) and packaging
889+(the files can be separately stored in a distribution package and installed
890+into the system-level XDG_DATA_DIR rather than the user-level folder).
891+
892+=== To create a database ===
893+
894+Create a file $XDG_DATA_DIR/desktop-couch/databases/YOUR_DB_NAME/database.cfg
895+
896+This file can currently be empty (in future it may contain database setup and
897+configuration information).
898+
899+=== To create a design document ===
900+
901+Create a file
902+$XDG_DATA_DIR/desktop-couch/databases/YOUR_DB_NAME/_design/DESIGN_DOC_NAME/views/VIEW_NAME/map.js
903+containing the map function from your view.
904+If you also require a reduce function for your view, create a file
905+$XDG_DATA_DIR/desktop-couch/databases/YOUR_DB_NAME/_design/DESIGN_DOC_NAME/views/VIEW_NAME/reduce.js.
906+
907+This is compatible with the filesystem view structure from CouchApp and
908+CouchDBKit.
909+
910
911=== added directory 'bin'
912=== added file 'bin/desktopcouch-pair'
913--- bin/desktopcouch-pair 1970-01-01 00:00:00 +0000
914+++ bin/desktopcouch-pair 2009-09-14 16:06:52 +0000
915@@ -0,0 +1,905 @@
916+#!/usr/bin/python
917+# Copyright 2009 Canonical Ltd.
918+#
919+# This file is part of desktopcouch.
920+#
921+# desktopcouch is free software: you can redistribute it and/or modify
922+# it under the terms of the GNU Lesser General Public License version 3
923+# as published by the Free Software Foundation.
924+#
925+# desktopcouch is distributed in the hope that it will be useful,
926+# but WITHOUT ANY WARRANTY; without even the implied warranty of
927+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
928+# GNU Lesser General Public License for more details.
929+#
930+# You should have received a copy of the GNU Lesser General Public License
931+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
932+# vim: filetype=python expandtab smarttab
933+
934+__doc__ = """\
935+Manage paired machines.
936+
937+A tool to set two local machines to replicate their couchdb instances to each
938+other, or to set this machine to replicate to-and-from Ubuntu One (and perhaps
939+other cloud services).
940+
941+Local-Pairing Authentication
942+----------------------------
943+
944+One machine, Alice, sets herself to listen for invitations to pair with another
945+machine. In doing so, Alice is discoverable via Zeroconf on local network.
946+
947+Another machine, Bob, sees the advertisement and generates a secret message and
948+a public seed. Bob then computes the SHA512 digest of the secret, and sends an
949+invitation to Alice, in the form of the hex digest concatenated with the public
950+seed. Bob displays the secret to the user, who walks the secret over to Alice.
951+
952+Alice then computes the SHA512 digest of Bob's secret and compares it to be
953+sure that the other machine is indeed the user's. Alice then concatenates
954+Bob's secret and the public seed, and sends the resulting hex digest back to
955+Bob to prove that she received the secret from the user. Alice sets herself to
956+replicate to Bob.
957+
958+Bob computes the secret+publicseed digest and compares it with the received hex
959+digest from Alice. When it matches, he sets himself to replicate to Alice.
960+"""
961+
962+
963+
964+import logging
965+import getpass
966+import gettext
967+# gettext implements "_" function. pylint: disable-msg=E0602
968+import random
969+import cgi
970+
971+from twisted.internet import gtk2reactor
972+gtk2reactor.install()
973+from twisted.internet.reactor import run as run_program
974+from twisted.internet.reactor import stop as stop_program
975+
976+import pygtk
977+pygtk.require('2.0')
978+import gtk
979+import gobject
980+import pango
981+
982+from desktopcouch.pair.couchdb_pairing import couchdb_io
983+from desktopcouch.pair.couchdb_pairing import network_io
984+from desktopcouch.pair.couchdb_pairing import dbus_io
985+from desktopcouch.pair.couchdb_pairing import couchdb_io
986+from desktopcouch.pair import pairing_record_type
987+from desktopcouch import local_files
988+
989+from desktopcouch.records.record import Record
990+
991+DISCOVERY_TOOL_VERSION = "1"
992+
993+def generate_secret(length=7):
994+ """Create a secret that is easy to write and read. We hate ambiguity and
995+ errors."""
996+
997+ pool = "abcdefghijklmnopqrstuvwxyz23456789#$%&*+=-"
998+ return unmap_easily_mistaken(
999+ "".join(random.choice(pool) for n in range(length)))
1000+
1001+def unmap_easily_mistaken(user_input):
1002+ """Returns ASCII-encoded text with visually-ambiguous characters crushed
1003+ down to some common atom."""
1004+
1005+ import string
1006+ easily_mistaken = string.maketrans("!10@", "lloo")
1007+ return string.translate(user_input.lower().encode("ascii"), easily_mistaken)
1008+
1009+def get_host_info():
1010+ """Create some text that hopefully identifies this host out of many."""
1011+
1012+ import platform
1013+
1014+ try:
1015+ uptime_seconds = int(float(file("/proc/uptime").read().split()[0]))
1016+ days, uptime_seconds = divmod(uptime_seconds, 60*60*24)
1017+ hours, uptime_seconds = divmod(uptime_seconds, 60*60)
1018+ minutes, seconds = divmod(uptime_seconds, 60)
1019+
1020+ # Is ISO8601 too nerdy? ...
1021+ #uptime_descr = ", up PT%(days)dD%(hours)dH%(minutes)dM" % locals()
1022+ uptime_descr = ", up %(days)dd %(hours)dh%(minutes)dm" % locals()
1023+ except OSError:
1024+ uptime_descr = ""
1025+
1026+ try:
1027+ return " ".join(platform.dist()) + uptime_descr
1028+ except AttributeError:
1029+ return platform.platform() + uptime_descr
1030+
1031+
1032+class Inviting:
1033+ """We're part of "Bob" in the module's story.
1034+
1035+ We see listeners on the network and send invitations to pair with us.
1036+ We generate a secret message and a public seed. We get the SHA512 hex
1037+ digest of the secret message, append the public seed and send it to
1038+ Alice. We also display the cleartext of the secret message to the
1039+ screen, so that the user can take it to the machine he thinks is Alice.
1040+
1041+ Eventually, we receive a message back from Alice. We compute the
1042+ secret message we started with concatenated with the public seed, and
1043+ if that matches Alice's message, then Alice must know the secret we
1044+ displayed to the user. We then set outselves to replicate to Alice."""
1045+
1046+ def delete_event(self, widget, event, data=None):
1047+ """User requested window be closed. False to propogate event."""
1048+ return False
1049+
1050+ def destroy(self, widget, data=None):
1051+ """The window is destroyed."""
1052+ self.inviter.close()
1053+
1054+ def auth_completed(self, remote_host, remote_id, remote_oauth):
1055+ """The auth stage is finished. Now pair with the remote host."""
1056+ pair_with_host(remote_host, remote_id, remote_oauth)
1057+ self.window.destroy()
1058+
1059+ def on_close(self):
1060+ """When a socket is closed, we should stop inviting. (?)"""
1061+ self.window.destroy()
1062+
1063+ def __init__(self, service, hostname, port):
1064+ self.logging = logging.getLogger(self.__class__.__name__)
1065+
1066+ self.hostname = hostname
1067+ self.port = port
1068+
1069+ self.window = gtk.Window()
1070+ self.window.set_border_width(6)
1071+ self.window.connect("delete_event", self.delete_event)
1072+ self.window.connect("destroy", self.destroy)
1073+ self.window.set_destroy_with_parent(True)
1074+ self.window.set_title(
1075+ _("Inviting %s to pair for CouchDB Pairing") % hostname)
1076+
1077+ secret_message = generate_secret()
1078+ self.secret_message = secret_message
1079+ self.public_seed = generate_secret()
1080+
1081+ self.inviter = network_io.start_send_invitation(hostname, port,
1082+ self.auth_completed, self.secret_message, self.public_seed,
1083+ self.on_close, couchdb_io.get_my_host_unique_id(create=True)[0],
1084+ local_files.get_oauth_tokens())
1085+
1086+ top_vbox = gtk.VBox()
1087+ self.window.add(top_vbox)
1088+
1089+ text = gtk.Label()
1090+ text.set_markup(_("""We're inviting %s to pair with\n""" +
1091+ """us, and to prove veracity of the invitation we\n""" +
1092+ """sent, it is waiting for you to tell it this secret:\n""" +
1093+ """<span font-size="xx-large" color="blue" weight="bold">""" +
1094+ """<tt>%s</tt></span> .""") %
1095+ (cgi.escape(service), cgi.escape(self.secret_message)))
1096+ text.set_justify(gtk.JUSTIFY_CENTER)
1097+ top_vbox.pack_start(text, False, False, 10)
1098+ text.show()
1099+
1100+ cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
1101+ cancel_button.set_border_width(3)
1102+ cancel_button.connect("clicked", lambda widget: self.window.destroy())
1103+ top_vbox.pack_end(cancel_button, False, False, 10)
1104+ cancel_button.show()
1105+
1106+ self.window.show_all()
1107+
1108+
1109+class AcceptInvitation:
1110+ """We're part of 'Alice' in this module's story.
1111+
1112+ We've received an invitation. We now send the other end a secret key. The
1113+ secret should make its way back to us via meatspace. We open a dialog
1114+ asking for that secret here, which we validate.
1115+
1116+ When we validate it, we add this end as replicating to the other end. The
1117+ other end should also set itself to replicate to us."""
1118+
1119+ def delete_event(self, widget, event, data=None):
1120+ """User requested window be closed. False to propogate event."""
1121+ return False
1122+
1123+ def destroy(self, widget, data=None):
1124+ """Window is destroyed."""
1125+ pass
1126+
1127+ def on_close(self):
1128+ """Handle communication channel being closed."""
1129+ # FIXME this is unimplemented and unused.
1130+ self.destroy()
1131+
1132+ def __init__(self, remote_host, is_secret_valid, send_valid_key,
1133+ remote_hostid, remote_oauth):
1134+ self.logging = logging.getLogger(self.__class__.__name__)
1135+
1136+ self.is_secret_valid = is_secret_valid
1137+ self.send_valid_key = send_valid_key
1138+
1139+ self.window = gtk.Window()
1140+ self.window.set_border_width(6)
1141+
1142+ self.logging.info("want to listen for invitations.")
1143+
1144+ self.window.connect("delete_event", self.delete_event)
1145+ self.window.connect("destroy", self.destroy)
1146+ self.window.set_destroy_with_parent(True)
1147+ self.window.set_title(_("Accepting Invitation"))
1148+
1149+ top_vbox = gtk.VBox()
1150+ top_vbox.show()
1151+ self.window.add(top_vbox)
1152+
1153+ self.remote_hostname = dbus_io.get_remote_hostname(remote_host)
1154+ self.remote_hostid = remote_hostid
1155+ self.remote_oauth = remote_oauth
1156+
1157+ description = gtk.Label(
1158+ _("To verify your pairing with %s, enter its secret.") %
1159+ self.remote_hostname)
1160+ description.show()
1161+ top_vbox.pack_start(description, False, False, 0)
1162+
1163+ self.entry_box = gtk.Entry(18)
1164+ self.entry_box.connect("activate", lambda widget: self.verify_secret())
1165+ #self.window.connect("activate", lambda widget: self.verify_secret())
1166+ self.entry_box.set_activates_default(True)
1167+ self.entry_box.show()
1168+ top_vbox.pack_start(self.entry_box, False, False, 0)
1169+
1170+ self.result = gtk.Label("")
1171+ self.result.show()
1172+ self.entry_box.connect("changed",
1173+ lambda widget: self.result.set_text(""))
1174+ top_vbox.pack_start(self.result, False, False, 0)
1175+
1176+ button_bar = gtk.HBox(homogeneous=True)
1177+ button_bar.show()
1178+ top_vbox.pack_end(button_bar, False, False, 10)
1179+
1180+ cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
1181+ cancel_button.set_border_width(3)
1182+ cancel_button.connect("clicked", lambda widget: self.window.destroy())
1183+ button_bar.pack_end(cancel_button, False, False, 10)
1184+ cancel_button.show()
1185+
1186+ connect_button = gtk.Button(_("Verify and connect"))
1187+ add_image = gtk.Image()
1188+ add_image.set_from_stock(gtk.STOCK_CONNECT, gtk.ICON_SIZE_BUTTON)
1189+ connect_button.set_image(add_image)
1190+ connect_button.set_border_width(3)
1191+ connect_button.connect("clicked", lambda widget: self.verify_secret())
1192+ button_bar.pack_end(connect_button, False, False, 10)
1193+ connect_button.show()
1194+
1195+ self.window.show_all()
1196+
1197+ def verify_secret(self):
1198+ """We got a sumbission from the user's fingers as to what he thinks
1199+ the secret is. We verify it, and if it's what the other end started
1200+ with, then it's okay to let us pair with it."""
1201+
1202+ proposed_secret = unmap_easily_mistaken(self.entry_box.get_text())
1203+ if self.is_secret_valid(proposed_secret):
1204+ pair_with_host(self.remote_hostname, self.remote_hostid,
1205+ self.remote_oauth)
1206+ self.send_valid_key(proposed_secret)
1207+ self.window.destroy()
1208+ else:
1209+ self.result.set_text("sorry, that is wrong")
1210+
1211+
1212+class Listening:
1213+ """We're part of 'Alice' in this module's story.
1214+
1215+ Window that starts listening for other machines to pick *us* to pair
1216+ with. There must be at least one of these on the network for pairing to
1217+ happen. We listen for a finite amount of time, and then stop."""
1218+
1219+ def delete_event(self, widget, event, data=None):
1220+ """User requested window be closed. False to propogate event."""
1221+ return False
1222+
1223+ def destroy(self, widget, data=None):
1224+ """Window is destroyed."""
1225+ self.timeout_counter = None
1226+
1227+ if self.advertisement is not None:
1228+ self.advertisement.die()
1229+ self.listener.close()
1230+
1231+ def receive_invitation_challenge(self, remote_address, is_secret_valid,
1232+ send_secret, remote_hostid, remote_oauth):
1233+ """When we receive an invitation, check its validity and if
1234+ it's what we expected, then continue and accept it."""
1235+
1236+ self.logging.warn("received invitation from %s", remote_address)
1237+ self.acceptor = AcceptInvitation(remote_address, is_secret_valid,
1238+ send_secret, remote_hostid, remote_oauth)
1239+ self.acceptor.window.connect("destroy",
1240+ lambda *args: setattr(self, "acceptor", None) and False)
1241+
1242+ def cancel_acceptor(self):
1243+ """Destroy window when connection canceled."""
1244+ self.acceptor.window.destroy()
1245+
1246+ def make_listener(self, couchdb_instance):
1247+ """Start listening for connections, and start advertising that
1248+ we're listening."""
1249+
1250+ self.listener = network_io.ListenForInvitations(
1251+ self.receive_invitation_challenge,
1252+ lambda: self.window.destroy(),
1253+ couchdb_io.get_my_host_unique_id(create=True)[0],
1254+ local_files.get_oauth_tokens())
1255+
1256+ listen_port = self.listener.get_local_port()
1257+
1258+ hostname, domainname = dbus_io.get_local_hostname()
1259+ username = getpass.getuser()
1260+ self.advertisement = dbus_io.PairAdvertisement(port=listen_port,
1261+ name="%s-%s-%d" % (hostname, username, listen_port),
1262+ text=dict(version=str(DISCOVERY_TOOL_VERSION),
1263+ description=get_host_info()))
1264+ self.advertisement.publish()
1265+ return hostname, username, listen_port
1266+
1267+ def __init__(self, couchdb_instance):
1268+ self.logging = logging.getLogger(self.__class__.__name__)
1269+
1270+ self.listener = None
1271+ self.listener_loop = None
1272+ self.advertisement = None
1273+ self.acceptor = None
1274+
1275+ self.timeout_counter = 180
1276+
1277+ self.window = gtk.Window()
1278+ self.window.set_border_width(6)
1279+
1280+ self.logging.info("want to listen for invitations.")
1281+
1282+ self.window.connect("delete_event", self.delete_event)
1283+ self.window.connect("destroy", self.destroy)
1284+ self.window.set_destroy_with_parent(True)
1285+ self.window.set_title(_("Waiting for CouchDB Pairing Invitations"))
1286+
1287+ top_vbox = gtk.VBox()
1288+ top_vbox.show()
1289+ self.window.add(top_vbox)
1290+
1291+ self.counter_text = gtk.Label("#")
1292+ self.counter_text.show()
1293+
1294+ top_vbox.pack_end(self.counter_text, False, False, 5)
1295+
1296+ button_bar = gtk.HBox(homogeneous=True)
1297+ button_bar.show()
1298+ top_vbox.pack_end(button_bar, False, False, 10)
1299+
1300+ cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
1301+ cancel_button.set_border_width(3)
1302+ cancel_button.connect("clicked", lambda *args: self.window.destroy())
1303+ button_bar.pack_end(cancel_button, False, False, 10)
1304+ cancel_button.show()
1305+
1306+ add_minute_button = gtk.Button(_("Add 60 seconds"))
1307+ add_image = gtk.Image()
1308+ add_image.set_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON)
1309+ add_minute_button.set_image(add_image)
1310+ add_minute_button.set_border_width(3)
1311+ add_minute_button.connect("clicked",
1312+ lambda widget: self.add_to_timeout_counter(60))
1313+ button_bar.pack_end(add_minute_button, False, False, 10)
1314+ add_minute_button.show()
1315+
1316+ hostid, userid, listen_port = self.make_listener(couchdb_instance)
1317+
1318+ text = gtk.Label()
1319+ text.set_markup(
1320+ _("""We're listening for invitations! From another\n""" +
1321+ """machine on this local network, run this\n""" +
1322+ """same tool and find the machine called\n""" +
1323+ """<span font-size="xx-large" weight="bold"><tt>""" +
1324+ """%s-%s-%d</tt></span> .""") %
1325+ (cgi.escape(hostid), cgi.escape(userid),
1326+ listen_port))
1327+ text.set_justify(gtk.JUSTIFY_CENTER)
1328+ top_vbox.pack_start(text, False, False, 10)
1329+ text.show()
1330+
1331+ self.update_counter_view()
1332+ self.window.show_all()
1333+
1334+ gobject.timeout_add(1000, self.decrement_counter)
1335+
1336+ def add_to_timeout_counter(self, seconds):
1337+ """The user wants more time. Add seconds to the clock."""
1338+ self.timeout_counter += seconds
1339+ self.update_counter_view()
1340+
1341+ def update_counter_view(self):
1342+ """Update the counter widget with pretty text."""
1343+ self.counter_text.set_text(
1344+ _("%d seconds remaining") % self.timeout_counter)
1345+
1346+ def decrement_counter(self):
1347+ """Tick! Decrement the counter and update the display."""
1348+ if self.timeout_counter is None:
1349+ return False
1350+
1351+ self.timeout_counter -= 1
1352+ if self.timeout_counter < 0:
1353+ self.window.destroy()
1354+ return False
1355+
1356+ self.update_counter_view()
1357+ return True
1358+
1359+
1360+class PickOrListen:
1361+ """Main top-level window that represents the life of the application."""
1362+
1363+ def delete_event(self, widget, event, data=None):
1364+ """User requested window be closed. False to propogate event."""
1365+ return False
1366+
1367+ def destroy(self, widget, data=None):
1368+ """The window was destroyed."""
1369+ stop_program()
1370+
1371+ def create_pick_pane(self, container):
1372+ """Set up the pane that contains what's necessary to choose an
1373+ already-listening tool instance. This sets up a "Bob" in the
1374+ module's story."""
1375+
1376+ # positions: host id, descr, host, port, cloud_name
1377+ self.listening_hosts = gtk.TreeStore(str, str, str, int, str)
1378+
1379+ import desktopcouch.replication_services as services
1380+
1381+ for srv_name in dir(services):
1382+ if srv_name.startswith("__"):
1383+ continue
1384+ srv = getattr(services, srv_name)
1385+ try:
1386+ if srv.is_active():
1387+ all_paired_cloud_servers = [x.key for x in
1388+ couchdb_io.get_pairings()]
1389+ if not srv_name in all_paired_cloud_servers:
1390+ self.listening_hosts.append(None,
1391+ [srv.name, srv.description, "", 0, srv_name])
1392+ except Exception, e:
1393+ self.logging.exception("service %r has errors", srv_name)
1394+
1395+ self.inviting = None # pylint: disable-msg=W0201
1396+
1397+ hostname_col = gtk.TreeViewColumn(_("hostname"))
1398+ hostid_col = gtk.TreeViewColumn(_("service name"))
1399+ description_col = gtk.TreeViewColumn(_("description"))
1400+
1401+ pick_box = gtk.VBox()
1402+ container.pack_start(pick_box, False, False, 10)
1403+
1404+ l = gtk.Label(_("Pick a listening host to invite it to pair with us."))
1405+ pick_box.pack_start(l, False, False, 0)
1406+ l.show()
1407+
1408+ tv = gtk.TreeView(self.listening_hosts)
1409+ tv.set_headers_visible(False)
1410+ tv.set_rules_hint(True)
1411+ tv.show()
1412+
1413+ def clicked(selection):
1414+ """An item in the list of services was clicked, so now we go
1415+ about inviting it to pair with us."""
1416+
1417+ model, iter = selection.get_selected()
1418+ if not iter:
1419+ return
1420+ service = model.get_value(iter, 0)
1421+ description = model.get_value(iter, 1)
1422+ hostname = model.get_value(iter, 2)
1423+ port = model.get_value(iter, 3)
1424+ service_name = model.get_value(iter, 4)
1425+
1426+ if service_name:
1427+ # Pairing with a cloud service, which doesn't do key exchange
1428+ pair_with_cloud_service(service_name)
1429+ # remove from listening list
1430+ self.listening_hosts.remove(iter)
1431+ # add to already-paired list
1432+ srv = getattr(services, service_name)
1433+ self.already_paired_hosts.append(None,
1434+ [service, _("paired just now"), hostname, port, service_name, None])
1435+ return
1436+
1437+ self.logging.info("connecting to %s:%s tcp to invite",
1438+ hostname, port)
1439+ if self.inviting != None:
1440+ self.inviting.window.destroy()
1441+ self.inviting = Inviting(service, hostname, port)
1442+ self.inviting.window.connect("destroy",
1443+ lambda *args: setattr(self, "inviting_window", None))
1444+
1445+ tv_selection = tv.get_selection()
1446+ tv_selection.connect("changed", clicked)
1447+
1448+ scrolled_window = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
1449+ scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
1450+ scrolled_window.set_border_width(10)
1451+ scrolled_window.add_with_viewport(tv)
1452+ scrolled_window.show()
1453+
1454+ pick_box.pack_start(scrolled_window, True, False, 0)
1455+
1456+ def add_service_to_list(name, description, host, port, version):
1457+ """When a zeroconf service appears, this adds it to the
1458+ listing of choices."""
1459+ self.listening_hosts.append(None, [name, description, host, port, None])
1460+
1461+ def remove_service_from_list(name):
1462+ """When a zeroconf service disappears, this finds it in the
1463+ listing and removes it as an option for picking."""
1464+
1465+ it = self.listening_hosts.get_iter_first()
1466+ while it is not None:
1467+ if self.listening_hosts.get_value(it, 0) == name:
1468+ self.listening_hosts.remove(it)
1469+ return True
1470+ it = self.listening_hosts.iter_next(it)
1471+
1472+ dbus_io.discover_services(add_service_to_list,
1473+ remove_service_from_list, show_local=False)
1474+
1475+ cell = gtk.CellRendererText()
1476+ tv.append_column(hostname_col)
1477+ hostname_col.pack_start(cell, True)
1478+ hostname_col.add_attribute(cell, 'text', 2)
1479+
1480+ cell = gtk.CellRendererText()
1481+ cell.set_property("weight", pango.WEIGHT_BOLD)
1482+ cell.set_property("weight-set", True)
1483+ tv.append_column(hostid_col)
1484+ hostid_col.pack_start(cell, True)
1485+ hostid_col.add_attribute(cell, 'text', 0)
1486+
1487+ cell = gtk.CellRendererText()
1488+ cell.set_property("ellipsize", pango.ELLIPSIZE_END)
1489+ cell.set_property("ellipsize-set", True)
1490+ tv.append_column(description_col)
1491+ description_col.pack_start(cell, True)
1492+ description_col.add_attribute(cell, 'text', 1)
1493+
1494+ return pick_box
1495+
1496+ def create_already_paired_pane(self, container):
1497+ """Set up the pane that shows servers which are already paired."""
1498+
1499+ # positions: host id, descr, host, port, cloud_name, pairingid
1500+ self.already_paired_hosts = gtk.TreeStore(str, str, str, int, str, str)
1501+
1502+ import desktopcouch.replication_services as services
1503+ for already_paired_record in couchdb_io.get_pairings():
1504+ pid = already_paired_record.value["pairing_identifier"]
1505+ if "service_name" in already_paired_record.value:
1506+ srv_name = already_paired_record.value["service_name"]
1507+ if srv_name.startswith("__"):
1508+ continue
1509+ srv = getattr(services, srv_name)
1510+ if not srv.is_active():
1511+ continue
1512+ if already_paired_record.value.get("unpaired", False):
1513+ continue
1514+ nice_description = _("paired ") + \
1515+ already_paired_record.value.get("ctime",
1516+ _("unknown date"))
1517+ try:
1518+ self.already_paired_hosts.append(None,
1519+ [srv.name, nice_description, "", 0, srv_name, pid])
1520+ except Exception, e:
1521+ logging.error("Service %s had an error", srv_name, e)
1522+ elif "server" in already_paired_record.value:
1523+ hostname = already_paired_record.value["server"]
1524+ nice_description = _("paired ") + \
1525+ already_paired_record.value.get("ctime",
1526+ _("unknown date"))
1527+ self.already_paired_hosts.append(None,
1528+ [hostname, nice_description, None, 0, None, pid])
1529+ else:
1530+ logging.error("unknown pairing record %s",
1531+ already_paired_record)
1532+
1533+ hostid_col = gtk.TreeViewColumn(_("service name"))
1534+ description_col = gtk.TreeViewColumn(_("service name"))
1535+
1536+ pick_box = gtk.VBox()
1537+ container.pack_start(pick_box, False, False, 10)
1538+
1539+ l = gtk.Label(_("You're currently paired with these hosts. Click to unpair."))
1540+ pick_box.pack_start(l, False, False, 0)
1541+ l.show()
1542+
1543+ tv = gtk.TreeView(self.already_paired_hosts)
1544+ tv.set_headers_visible(False)
1545+ tv.set_rules_hint(True)
1546+ tv.show()
1547+
1548+ def clicked(selection):
1549+ """An item in the list of services was clicked, so now we go
1550+ about inviting it to pair with us."""
1551+
1552+ model, iter = selection.get_selected()
1553+ if not iter:
1554+ return
1555+ service = model.get_value(iter, 0)
1556+ hostname = model.get_value(iter, 2)
1557+ port = model.get_value(iter, 3)
1558+ service_name = model.get_value(iter, 4)
1559+ pid = model.get_value(iter, 5)
1560+
1561+ if service_name:
1562+ # delete record
1563+ for record in couchdb_io.get_pairings():
1564+ couchdb_io.remove_pairing(record.id, True)
1565+
1566+ # remove from already-paired list
1567+ self.already_paired_hosts.remove(iter)
1568+ # add to listening list
1569+ srv = getattr(services, service_name)
1570+ self.listening_hosts.append(None, [service, srv.description,
1571+ hostname, port, service_name])
1572+ return
1573+
1574+ # delete (really, mark as "unpaired")
1575+ for record in couchdb_io.get_pairings():
1576+ if record.value["pairing_identifier"] == pid:
1577+ couchdb_io.remove_pairing(record.id, False)
1578+ break
1579+
1580+ # remove from already-paired list
1581+ self.already_paired_hosts.remove(iter)
1582+ # do not add to listening list -- if it's listening then zeroconf
1583+ # will pick it up
1584+ return
1585+
1586+ tv_selection = tv.get_selection()
1587+ tv_selection.connect("changed", clicked)
1588+
1589+ scrolled_window = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
1590+ scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
1591+ scrolled_window.set_border_width(10)
1592+ scrolled_window.add_with_viewport(tv)
1593+ scrolled_window.show()
1594+
1595+ pick_box.pack_start(scrolled_window, True, False, 0)
1596+
1597+ cell = gtk.CellRendererText()
1598+ tv.append_column(hostid_col)
1599+ hostid_col.pack_start(cell, True)
1600+ hostid_col.add_attribute(cell, 'text', 0)
1601+
1602+ cell = gtk.CellRendererText()
1603+ cell.set_property("ellipsize", pango.ELLIPSIZE_END)
1604+ cell.set_property("ellipsize-set", True)
1605+ tv.append_column(description_col)
1606+ description_col.pack_start(cell, True)
1607+ description_col.add_attribute(cell, 'text', 1)
1608+
1609+ return pick_box
1610+
1611+ def create_single_listen_pane(self, container):
1612+ """This sets up an "Alice" from the module's story.
1613+
1614+ This assumes we're pairing a single, known local CouchDB instance,
1615+ instead of generic instances that we'd need more information to talk
1616+ about. Instead of using this function, one might use another that
1617+ lists local DBs as a way of picking one to pair. This function assumes
1618+ we know the answer to that."""
1619+
1620+ def listen(btn, couchdb_instance=None):
1621+ """When we decide to listen for invitations, this spawns the
1622+ advertising/information window, and disables the button that
1623+ causes/-ed us to get here (to prevent multiple instances)."""
1624+
1625+ if couchdb_instance is None:
1626+ # assume local for this user. FIXME
1627+ pass
1628+
1629+ btn.set_sensitive(False)
1630+ listening = Listening(couchdb_instance)
1631+ listening.window.connect("destroy",
1632+ lambda w: btn.set_sensitive(True))
1633+
1634+ padding = 6
1635+
1636+ listen_box = gtk.HBox()
1637+ container.pack_start(listen_box, False, False, 2)
1638+
1639+ l = gtk.Label(_("Add this host to the list for others to see?"))
1640+ listen_box.pack_start(l, True, False, padding)
1641+ l.show()
1642+
1643+ listen_button = gtk.Button(_("Listen for invitations"))
1644+ listen_button.connect("clicked", listen, None)
1645+ listen_box.pack_start(listen_button, True, False, padding)
1646+ listen_button.show()
1647+
1648+ return listen_box
1649+
1650+ def create_any_listen_pane(self, container):
1651+ """Unused. An example of where to start when we don't already have
1652+ a couchdb instance in mind to advertise. This should be the generic
1653+ version."""
1654+
1655+ l = gtk.Label(_("I also know of CouchDB sessions here. Pick one " +
1656+ "to add it to the invitation list for other computers to see."))
1657+
1658+ local_sharables_list = gtk.TreeStore(str, str)
1659+ # et c, et c
1660+ #some_row_in_list.connect("clicked", self.listen, target_db_info)
1661+
1662+ def __init__(self):
1663+
1664+
1665+ self.logging = logging.getLogger(self.__class__.__name__)
1666+
1667+ self.window = gtk.Window()
1668+
1669+ self.window.connect("delete_event", self.delete_event)
1670+ self.window.connect("destroy", self.destroy)
1671+
1672+ self.window.set_border_width(8)
1673+ self.window.set_title(_("CouchDB Pairing Tool"))
1674+
1675+ top_vbox = gtk.VBox()
1676+ self.window.add(top_vbox)
1677+
1678+ self.pick_pane = self.create_pick_pane(top_vbox)
1679+ self.listen_pane = self.create_single_listen_pane(top_vbox)
1680+ seperator = gtk.HSeparator()
1681+ top_vbox.pack_start(seperator, False, False, 10)
1682+ seperator.show()
1683+ self.already_paired_pane = self.create_already_paired_pane(top_vbox)
1684+
1685+ copyright = gtk.Label(_("Copyright 2009 Canonical"))
1686+ top_vbox.pack_end(copyright, False, False, 0)
1687+ copyright.show()
1688+
1689+ self.pick_pane.show()
1690+ self.listen_pane.show()
1691+ self.already_paired_pane.show()
1692+
1693+ top_vbox.show()
1694+ self.window.show()
1695+
1696+
1697+def pair_with_host(hostname, hostid, oauth_data):
1698+ """We've verified all is correct and authorized, so now we pair
1699+ the databases."""
1700+ logging.info("verified host %s/%s. Done!", hostname, hostid)
1701+
1702+ try:
1703+ result = couchdb_io.put_dynamic_paired_host(hostname, hostid, oauth_data)
1704+ assert result is not None
1705+ except Exception, e:
1706+ logging.exception("failure writing record for %s", hostname)
1707+ fail_note = gtk.MessageDialog(
1708+ parent=pick_or_listen.window,
1709+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1710+ buttons=gtk.BUTTONS_OK,
1711+ type=gtk.MESSAGE_ERROR,
1712+ message_format =_("Couldn't save pairing details for %s") % hostname)
1713+ fail_note.run()
1714+ fail_note.destroy()
1715+ return
1716+
1717+ success_note = gtk.Dialog(title=_("Paired with %(hostname)s") % locals(),
1718+ parent=pick_or_listen.window,
1719+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1720+ buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,))
1721+ text = gtk.Label(
1722+ _("Successfully paired with %(hostname)s.") % locals())
1723+ text.show()
1724+ content_box = success_note.get_content_area()
1725+ content_box.pack_start(text, True, True, 20)
1726+ success_note.connect("close",
1727+ lambda *args: pick_or_listen.window.destroy())
1728+ success_note.connect("response",
1729+ lambda *args: pick_or_listen.window.destroy())
1730+ success_note.show()
1731+
1732+
1733+def pair_with_cloud_service(service_name):
1734+ """Write a paired server record for the selected cloud service."""
1735+ try:
1736+ import desktopcouch.replication_services as services
1737+ srv = getattr(services, service_name)
1738+ oauth_data = srv.oauth_data()
1739+ result = couchdb_io.put_static_paired_service(oauth_data, service_name)
1740+ assert result != None
1741+ except Exception, e:
1742+ logging.exception("failure in module for service %r", service_name)
1743+ fail_note = gtk.MessageDialog(
1744+ parent=pick_or_listen.window,
1745+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1746+ buttons=gtk.BUTTONS_OK,
1747+ type=gtk.MESSAGE_ERROR,
1748+ message_format =_("Couldn't save pairing details for %r") % service_name)
1749+ fail_note.run()
1750+ fail_note.destroy()
1751+ return
1752+
1753+ success_note = gtk.MessageDialog(
1754+ parent=pick_or_listen.window,
1755+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1756+ buttons=gtk.BUTTONS_OK,
1757+ type=gtk.MESSAGE_INFO,
1758+ message_format =_("Successfully paired with %s") % service_name)
1759+ success_note.run()
1760+ success_note.destroy()
1761+
1762+
1763+def set_couchdb_bind_address():
1764+ from desktopcouch.records.server import CouchDatabase
1765+ from desktopcouch import local_files
1766+ bind_address = local_files.get_bind_address()
1767+
1768+ if bind_address not in ("127.0.0.1", "0.0.0.0", "::1", None):
1769+ logging.info("we're not qualified to change explicit address %s",
1770+ bind_address)
1771+ return False
1772+
1773+ db = CouchDatabase("management", create=True)
1774+ results = db.get_records(create_view=True)
1775+ count = 0
1776+ for row in results[pairing_record_type]:
1777+ # Is the record of something that probably connects back to us?
1778+ if "server" in row.value and row.value["server"] != "":
1779+ count += 1
1780+ logging.debug("paired back-connecting machine count is %d", count)
1781+ if count > 0:
1782+ couchdb_io.get_my_host_unique_id(create=True) # ensure self-id record
1783+ if ":" in bind_address:
1784+ want_bind_address = "::0" # IPv6 addr any
1785+ else:
1786+ want_bind_address = "0.0.0.0"
1787+ else:
1788+ if ":" in bind_address:
1789+ want_bind_address = "::1" # IPv6 loop back
1790+ else:
1791+ want_bind_address = "127.0.0.1"
1792+
1793+ if bind_address != want_bind_address:
1794+ local_files.set_bind_address(want_bind_address)
1795+ logging.warning("changing the desktopcouch bind address from %r to %r",
1796+ bind_address, want_bind_address)
1797+
1798+def main(args):
1799+ """Start execution."""
1800+ global pick_or_listen # pylint: disable-msg=W0601
1801+
1802+ logging.basicConfig(level=logging.DEBUG, format=
1803+ "%(asctime)s [%(process)d] %(name)s:%(levelname)s: %(message)s")
1804+
1805+ gettext.install("couchdb_pairing")
1806+
1807+ try:
1808+ logging.debug("starting couchdb pairing tool")
1809+ pick_or_listen = PickOrListen()
1810+ return run_program()
1811+ finally:
1812+ set_couchdb_bind_address()
1813+ logging.debug("exiting couchdb pairing tool")
1814+
1815+
1816+if __name__ == "__main__":
1817+ import sys
1818+ import desktopcouch
1819+ desktopcouch_port = desktopcouch.find_port()
1820+ main(sys.argv)
1821
1822=== added file 'bin/desktopcouch-service'
1823--- bin/desktopcouch-service 1970-01-01 00:00:00 +0000
1824+++ bin/desktopcouch-service 2009-09-11 03:18:00 +0000
1825@@ -0,0 +1,108 @@
1826+#!/usr/bin/python
1827+# Copyright 2009 Canonical Ltd.
1828+#
1829+# This file is part of desktopcouch.
1830+#
1831+# desktopcouch is free software: you can redistribute it and/or modify
1832+# it under the terms of the GNU Lesser General Public License version 3
1833+# as published by the Free Software Foundation.
1834+#
1835+# desktopcouch is distributed in the hope that it will be useful,
1836+# but WITHOUT ANY WARRANTY; without even the implied warranty of
1837+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1838+# GNU Lesser General Public License for more details.
1839+#
1840+# You should have received a copy of the GNU Lesser General Public License
1841+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
1842+#
1843+# Authors: Stuart Langridge <stuart.langridge@canonical.com>
1844+# Tim Cole <tim.cole@canonical.com>
1845+
1846+"""CouchDB port advertiser.
1847+
1848+A command-line utility which exports a
1849+desktopCouch.getPort method on the bus which returns
1850+that port, so other apps (specifically, the contacts API) can work out
1851+where CouchDB is running so it can be talked to.
1852+
1853+Calculates the port number by looking in the CouchDB log.
1854+
1855+If CouchDB is not running, then run the script to start it and then
1856+start advertising the port.
1857+
1858+This file should be started by D-Bus activation.
1859+
1860+"""
1861+
1862+import logging
1863+import logging.handlers
1864+from errno import ENOENT
1865+
1866+from twisted.internet import glib2reactor
1867+glib2reactor.install()
1868+from twisted.internet import reactor
1869+import dbus.service, gobject, os, errno, time
1870+
1871+import desktopcouch
1872+from desktopcouch import local_files
1873+from desktopcouch import replication
1874+
1875+
1876+class PortAdvertiser(dbus.service.Object):
1877+ "Advertise the discovered port number on the D-Bus Session bus"
1878+ def __init__(self, death):
1879+ bus_name = dbus.service.BusName("org.desktopcouch.CouchDB",
1880+ bus=dbus.SessionBus())
1881+ self.death = death
1882+ dbus.service.Object.__init__(self, object_path="/", bus_name=bus_name)
1883+
1884+ @dbus.service.method(dbus_interface='org.desktopcouch.CouchDB',
1885+ in_signature='', out_signature='i')
1886+ def getPort(self):
1887+ "Exported method to return the port"
1888+ return int(desktopcouch.find_port())
1889+
1890+ @dbus.service.method(dbus_interface='org.desktopcouch.CouchDB',
1891+ in_signature='', out_signature='')
1892+ def quit(self):
1893+ "Exported method to quit the program"
1894+ self.death()
1895+
1896+if __name__ == "__main__":
1897+ import xdg.BaseDirectory
1898+
1899+ log_directory = os.path.join(xdg.BaseDirectory.xdg_cache_home,
1900+ "ubuntuone/log")
1901+ try:
1902+ os.makedirs(log_directory)
1903+ except:
1904+ pass
1905+ rotating_log = logging.handlers.TimedRotatingFileHandler(
1906+ os.path.join(log_directory, "desktop-couch-replication.log"),
1907+ "midnight", 1, 14)
1908+ rotating_log.setLevel(logging.DEBUG)
1909+ formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
1910+ rotating_log.setFormatter(formatter)
1911+ logging.getLogger('').addHandler(rotating_log)
1912+ console_log = logging.StreamHandler()
1913+ console_log.setLevel(logging.WARNING)
1914+ console_log.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))
1915+ logging.getLogger('').addHandler(console_log)
1916+ logging.getLogger('').setLevel(logging.DEBUG)
1917+
1918+
1919+ # Advertise the port
1920+ mainloop = reactor
1921+
1922+ portAdvertiser = PortAdvertiser(mainloop.stop)
1923+
1924+ replication_runtime = replication.set_up(desktopcouch.find_port)
1925+ try:
1926+
1927+ mainloop.run()
1928+
1929+ finally:
1930+ if replication_runtime:
1931+ print "Shutting down, but may be a moment to finish replication."
1932+ replication.tear_down(*replication_runtime)
1933+
1934
1935=== added file 'bin/desktopcouch-stop'
1936--- bin/desktopcouch-stop 1970-01-01 00:00:00 +0000
1937+++ bin/desktopcouch-stop 2009-07-24 19:32:52 +0000
1938@@ -0,0 +1,36 @@
1939+#!/usr/bin/python
1940+# Copyright 2009 Canonical Ltd.
1941+#
1942+# This file is part of desktopcouch.
1943+#
1944+# desktopcouch is free software: you can redistribute it and/or modify
1945+# it under the terms of the GNU Lesser General Public License version 3
1946+# as published by the Free Software Foundation.
1947+#
1948+# desktopcouch is distributed in the hope that it will be useful,
1949+# but WITHOUT ANY WARRANTY; without even the implied warranty of
1950+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1951+# GNU Lesser General Public License for more details.
1952+#
1953+# You should have received a copy of the GNU Lesser General Public License
1954+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
1955+#
1956+# Author: Stuart Langridge <stuart.langridge@canonical.com>
1957+"""
1958+Stop local CouchDB server.
1959+"""
1960+import subprocess, sys
1961+from desktopcouch import local_files
1962+
1963+local_exec = local_files.COUCH_EXEC_COMMAND + ["-k"]
1964+try:
1965+ retcode = subprocess.call(local_exec, shell=False)
1966+ if retcode < 0:
1967+ print >> sys.stderr, "Child was terminated by signal", -retcode
1968+ elif retcode > 0:
1969+ print >> sys.stderr, "Child returned", retcode
1970+except OSError, e:
1971+ print >> sys.stderr, "Execution failed: %s: %s" % (e, local_exec)
1972+ exit(1)
1973+
1974+
1975
1976=== added directory 'config'
1977=== added directory 'config/desktop-couch'
1978=== added file 'config/desktop-couch/compulsory-auth.ini'
1979--- config/desktop-couch/compulsory-auth.ini 1970-01-01 00:00:00 +0000
1980+++ config/desktop-couch/compulsory-auth.ini 2009-09-11 19:08:53 +0000
1981@@ -0,0 +1,3 @@
1982+[couch_httpd_auth]
1983+require_valid_user = true
1984+
1985
1986=== added directory 'contrib'
1987=== added file 'contrib/mocker.py'
1988--- contrib/mocker.py 1970-01-01 00:00:00 +0000
1989+++ contrib/mocker.py 2009-08-06 13:57:30 +0000
1990@@ -0,0 +1,2068 @@
1991+"""
1992+Copyright (c) 2007 Gustavo Niemeyer <gustavo@niemeyer.net>
1993+
1994+Graceful platform for test doubles in Python (mocks, stubs, fakes, and dummies).
1995+"""
1996+import __builtin__
1997+import tempfile
1998+import unittest
1999+import inspect
2000+import shutil
2001+import types
2002+import sys
2003+import os
2004+import gc
2005+
2006+
2007+if sys.version_info < (2, 4):
2008+ from sets import Set as set # pragma: nocover
2009+
2010+
2011+__all__ = ["Mocker", "expect", "IS", "CONTAINS", "IN", "MATCH",
2012+ "ANY", "ARGS", "KWARGS"]
2013+
2014+
2015+__author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>"
2016+__license__ = "PSF License"
2017+__version__ = "0.10.1"
2018+
2019+
2020+ERROR_PREFIX = "[Mocker] "
2021+
2022+
2023+# --------------------------------------------------------------------
2024+# Exceptions
2025+
2026+class MatchError(AssertionError):
2027+ """Raised when an unknown expression is seen in playback mode."""
2028+
2029+
2030+# --------------------------------------------------------------------
2031+# Helper for chained-style calling.
2032+
2033+class expect(object):
2034+ """This is a simple helper that allows a different call-style.
2035+
2036+ With this class one can comfortably do chaining of calls to the
2037+ mocker object responsible by the object being handled. For instance::
2038+
2039+ expect(obj.attr).result(3).count(1, 2)
2040+
2041+ Is the same as::
2042+
2043+ obj.attr
2044+ mocker.result(3)
2045+ mocker.count(1, 2)
2046+
2047+ """
2048+
2049+ def __init__(self, mock, attr=None):
2050+ self._mock = mock
2051+ self._attr = attr
2052+
2053+ def __getattr__(self, attr):
2054+ return self.__class__(self._mock, attr)
2055+
2056+ def __call__(self, *args, **kwargs):
2057+ getattr(self._mock.__mocker__, self._attr)(*args, **kwargs)
2058+ return self
2059+
2060+
2061+# --------------------------------------------------------------------
2062+# Extensions to Python's unittest.
2063+
2064+class MockerTestCase(unittest.TestCase):
2065+ """unittest.TestCase subclass with Mocker support.
2066+
2067+ @ivar mocker: The mocker instance.
2068+
2069+ This is a convenience only. Mocker may easily be used with the
2070+ standard C{unittest.TestCase} class if wanted.
2071+
2072+ Test methods have a Mocker instance available on C{self.mocker}.
2073+ At the end of each test method, expectations of the mocker will
2074+ be verified, and any requested changes made to the environment
2075+ will be restored.
2076+
2077+ In addition to the integration with Mocker, this class provides
2078+ a few additional helper methods.
2079+ """
2080+
2081+ expect = expect
2082+
2083+ def __init__(self, methodName="runTest"):
2084+ # So here is the trick: we take the real test method, wrap it on
2085+ # a function that do the job we have to do, and insert it in the
2086+ # *instance* dictionary, so that getattr() will return our
2087+ # replacement rather than the class method.
2088+ test_method = getattr(self, methodName, None)
2089+ if test_method is not None:
2090+ def test_method_wrapper():
2091+ try:
2092+ result = test_method()
2093+ except:
2094+ raise
2095+ else:
2096+ if (self.mocker.is_recording() and
2097+ self.mocker.get_events()):
2098+ raise RuntimeError("Mocker must be put in replay "
2099+ "mode with self.mocker.replay()")
2100+ if (hasattr(result, "addCallback") and
2101+ hasattr(result, "addErrback")):
2102+ def verify(result):
2103+ self.mocker.verify()
2104+ return result
2105+ result.addCallback(verify)
2106+ else:
2107+ self.mocker.verify()
2108+ return result
2109+ # Copy all attributes from the original method..
2110+ for attr in dir(test_method):
2111+ # .. unless they're present in our wrapper already.
2112+ if not hasattr(test_method_wrapper, attr) or attr == "__doc__":
2113+ setattr(test_method_wrapper, attr,
2114+ getattr(test_method, attr))
2115+ setattr(self, methodName, test_method_wrapper)
2116+
2117+ # We could overload run() normally, but other well-known testing
2118+ # frameworks do it as well, and some of them won't call the super,
2119+ # which might mean that cleanup wouldn't happen. With that in mind,
2120+ # we make integration easier by using the following trick.
2121+ run_method = self.run
2122+ def run_wrapper(*args, **kwargs):
2123+ try:
2124+ return run_method(*args, **kwargs)
2125+ finally:
2126+ self.__cleanup()
2127+ self.run = run_wrapper
2128+
2129+ self.mocker = Mocker()
2130+
2131+ self.__cleanup_funcs = []
2132+ self.__cleanup_paths = []
2133+
2134+ super(MockerTestCase, self).__init__(methodName)
2135+
2136+ def __cleanup(self):
2137+ for path in self.__cleanup_paths:
2138+ if os.path.isfile(path):
2139+ os.unlink(path)
2140+ elif os.path.isdir(path):
2141+ shutil.rmtree(path)
2142+ self.mocker.restore()
2143+ for func, args, kwargs in self.__cleanup_funcs:
2144+ func(*args, **kwargs)
2145+
2146+ def addCleanup(self, func, *args, **kwargs):
2147+ self.__cleanup_funcs.append((func, args, kwargs))
2148+
2149+ def makeFile(self, content=None, suffix="", prefix="tmp", basename=None,
2150+ dirname=None, path=None):
2151+ """Create a temporary file and return the path to it.
2152+
2153+ @param content: Initial content for the file.
2154+ @param suffix: Suffix to be given to the file's basename.
2155+ @param prefix: Prefix to be given to the file's basename.
2156+ @param basename: Full basename for the file.
2157+ @param dirname: Put file inside this directory.
2158+
2159+ The file is removed after the test runs.
2160+ """
2161+ if path is not None:
2162+ self.__cleanup_paths.append(path)
2163+ elif basename is not None:
2164+ if dirname is None:
2165+ dirname = tempfile.mkdtemp()
2166+ self.__cleanup_paths.append(dirname)
2167+ path = os.path.join(dirname, basename)
2168+ else:
2169+ fd, path = tempfile.mkstemp(suffix, prefix, dirname)
2170+ self.__cleanup_paths.append(path)
2171+ os.close(fd)
2172+ if content is None:
2173+ os.unlink(path)
2174+ if content is not None:
2175+ file = open(path, "w")
2176+ file.write(content)
2177+ file.close()
2178+ return path
2179+
2180+ def makeDir(self, suffix="", prefix="tmp", dirname=None, path=None):
2181+ """Create a temporary directory and return the path to it.
2182+
2183+ @param suffix: Suffix to be given to the file's basename.
2184+ @param prefix: Prefix to be given to the file's basename.
2185+ @param dirname: Put directory inside this parent directory.
2186+
2187+ The directory is removed after the test runs.
2188+ """
2189+ if path is not None:
2190+ os.makedirs(path)
2191+ else:
2192+ path = tempfile.mkdtemp(suffix, prefix, dirname)
2193+ self.__cleanup_paths.append(path)
2194+ return path
2195+
2196+ def failUnlessIs(self, first, second, msg=None):
2197+ """Assert that C{first} is the same object as C{second}."""
2198+ if first is not second:
2199+ raise self.failureException(msg or "%r is not %r" % (first, second))
2200+
2201+ def failIfIs(self, first, second, msg=None):
2202+ """Assert that C{first} is not the same object as C{second}."""
2203+ if first is second:
2204+ raise self.failureException(msg or "%r is %r" % (first, second))
2205+
2206+ def failUnlessIn(self, first, second, msg=None):
2207+ """Assert that C{first} is contained in C{second}."""
2208+ if first not in second:
2209+ raise self.failureException(msg or "%r not in %r" % (first, second))
2210+
2211+ def failUnlessStartsWith(self, first, second, msg=None):
2212+ """Assert that C{first} starts with C{second}."""
2213+ if first[:len(second)] != second:
2214+ raise self.failureException(msg or "%r doesn't start with %r" %
2215+ (first, second))
2216+
2217+ def failIfStartsWith(self, first, second, msg=None):
2218+ """Assert that C{first} doesn't start with C{second}."""
2219+ if first[:len(second)] == second:
2220+ raise self.failureException(msg or "%r starts with %r" %
2221+ (first, second))
2222+
2223+ def failUnlessEndsWith(self, first, second, msg=None):
2224+ """Assert that C{first} starts with C{second}."""
2225+ if first[len(first)-len(second):] != second:
2226+ raise self.failureException(msg or "%r doesn't end with %r" %
2227+ (first, second))
2228+
2229+ def failIfEndsWith(self, first, second, msg=None):
2230+ """Assert that C{first} doesn't start with C{second}."""
2231+ if first[len(first)-len(second):] == second:
2232+ raise self.failureException(msg or "%r ends with %r" %
2233+ (first, second))
2234+
2235+ def failIfIn(self, first, second, msg=None):
2236+ """Assert that C{first} is not contained in C{second}."""
2237+ if first in second:
2238+ raise self.failureException(msg or "%r in %r" % (first, second))
2239+
2240+ def failUnlessApproximates(self, first, second, tolerance, msg=None):
2241+ """Assert that C{first} is near C{second} by at most C{tolerance}."""
2242+ if abs(first - second) > tolerance:
2243+ raise self.failureException(msg or "abs(%r - %r) > %r" %
2244+ (first, second, tolerance))
2245+
2246+ def failIfApproximates(self, first, second, tolerance, msg=None):
2247+ """Assert that C{first} is far from C{second} by at least C{tolerance}.
2248+ """
2249+ if abs(first - second) <= tolerance:
2250+ raise self.failureException(msg or "abs(%r - %r) <= %r" %
2251+ (first, second, tolerance))
2252+
2253+ def failUnlessMethodsMatch(self, first, second):
2254+ """Assert that public methods in C{first} are present in C{second}.
2255+
2256+ This method asserts that all public methods found in C{first} are also
2257+ present in C{second} and accept the same arguments. C{first} may
2258+ have its own private methods, though, and may not have all methods
2259+ found in C{second}. Note that if a private method in C{first} matches
2260+ the name of one in C{second}, their specification is still compared.
2261+
2262+ This is useful to verify if a fake or stub class have the same API as
2263+ the real class being simulated.
2264+ """
2265+ first_methods = dict(inspect.getmembers(first, inspect.ismethod))
2266+ second_methods = dict(inspect.getmembers(second, inspect.ismethod))
2267+ for name, first_method in first_methods.items():
2268+ first_argspec = inspect.getargspec(first_method)
2269+ first_formatted = inspect.formatargspec(*first_argspec)
2270+
2271+ second_method = second_methods.get(name)
2272+ if second_method is None:
2273+ if name[:1] == "_":
2274+ continue # First may have its own private methods.
2275+ raise self.failureException("%s.%s%s not present in %s" %
2276+ (first.__name__, name, first_formatted, second.__name__))
2277+
2278+ second_argspec = inspect.getargspec(second_method)
2279+ if first_argspec != second_argspec:
2280+ second_formatted = inspect.formatargspec(*second_argspec)
2281+ raise self.failureException("%s.%s%s != %s.%s%s" %
2282+ (first.__name__, name, first_formatted,
2283+ second.__name__, name, second_formatted))
2284+
2285+
2286+ assertIs = failUnlessIs
2287+ assertIsNot = failIfIs
2288+ assertIn = failUnlessIn
2289+ assertNotIn = failIfIn
2290+ assertStartsWith = failUnlessStartsWith
2291+ assertNotStartsWith = failIfStartsWith
2292+ assertEndsWith = failUnlessEndsWith
2293+ assertNotEndsWith = failIfEndsWith
2294+ assertApproximates = failUnlessApproximates
2295+ assertNotApproximates = failIfApproximates
2296+ assertMethodsMatch = failUnlessMethodsMatch
2297+
2298+ # The following are missing in Python < 2.4.
2299+ assertTrue = unittest.TestCase.failUnless
2300+ assertFalse = unittest.TestCase.failIf
2301+
2302+ # The following is provided for compatibility with Twisted's trial.
2303+ assertIdentical = assertIs
2304+ assertNotIdentical = assertIsNot
2305+ failUnlessIdentical = failUnlessIs
2306+ failIfIdentical = failIfIs
2307+
2308+
2309+# --------------------------------------------------------------------
2310+# Mocker.
2311+
2312+class classinstancemethod(object):
2313+
2314+ def __init__(self, method):
2315+ self.method = method
2316+
2317+ def __get__(self, obj, cls=None):
2318+ def bound_method(*args, **kwargs):
2319+ return self.method(cls, obj, *args, **kwargs)
2320+ return bound_method
2321+
2322+
2323+class MockerBase(object):
2324+ """Controller of mock objects.
2325+
2326+ A mocker instance is used to command recording and replay of
2327+ expectations on any number of mock objects.
2328+
2329+ Expectations should be expressed for the mock object while in
2330+ record mode (the initial one) by using the mock object itself,
2331+ and using the mocker (and/or C{expect()} as a helper) to define
2332+ additional behavior for each event. For instance::
2333+
2334+ mock = mocker.mock()
2335+ mock.hello()
2336+ mocker.result("Hi!")
2337+ mocker.replay()
2338+ assert mock.hello() == "Hi!"
2339+ mock.restore()
2340+ mock.verify()
2341+
2342+ In this short excerpt a mock object is being created, then an
2343+ expectation of a call to the C{hello()} method was recorded, and
2344+ when called the method should return the value C{10}. Then, the
2345+ mocker is put in replay mode, and the expectation is satisfied by
2346+ calling the C{hello()} method, which indeed returns 10. Finally,
2347+ a call to the L{restore()} method is performed to undo any needed
2348+ changes made in the environment, and the L{verify()} method is
2349+ called to ensure that all defined expectations were met.
2350+
2351+ The same logic can be expressed more elegantly using the
2352+ C{with mocker:} statement, as follows::
2353+
2354+ mock = mocker.mock()
2355+ mock.hello()
2356+ mocker.result("Hi!")
2357+ with mocker:
2358+ assert mock.hello() == "Hi!"
2359+
2360+ Also, the MockerTestCase class, which integrates the mocker on
2361+ a unittest.TestCase subclass, may be used to reduce the overhead
2362+ of controlling the mocker. A test could be written as follows::
2363+
2364+ class SampleTest(MockerTestCase):
2365+
2366+ def test_hello(self):
2367+ mock = self.mocker.mock()
2368+ mock.hello()
2369+ self.mocker.result("Hi!")
2370+ self.mocker.replay()
2371+ self.assertEquals(mock.hello(), "Hi!")
2372+ """
2373+
2374+ _recorders = []
2375+
2376+ # For convenience only.
2377+ on = expect
2378+
2379+ class __metaclass__(type):
2380+ def __init__(self, name, bases, dict):
2381+ # Make independent lists on each subclass, inheriting from parent.
2382+ self._recorders = list(getattr(self, "_recorders", ()))
2383+
2384+ def __init__(self):
2385+ self._recorders = self._recorders[:]
2386+ self._events = []
2387+ self._recording = True
2388+ self._ordering = False
2389+ self._last_orderer = None
2390+
2391+ def is_recording(self):
2392+ """Return True if in recording mode, False if in replay mode.
2393+
2394+ Recording is the initial state.
2395+ """
2396+ return self._recording
2397+
2398+ def replay(self):
2399+ """Change to replay mode, where recorded events are reproduced.
2400+
2401+ If already in replay mode, the mocker will be restored, with all
2402+ expectations reset, and then put again in replay mode.
2403+
2404+ An alternative and more comfortable way to replay changes is
2405+ using the 'with' statement, as follows::
2406+
2407+ mocker = Mocker()
2408+ <record events>
2409+ with mocker:
2410+ <reproduce events>
2411+
2412+ The 'with' statement will automatically put mocker in replay
2413+ mode, and will also verify if all events were correctly reproduced
2414+ at the end (using L{verify()}), and also restore any changes done
2415+ in the environment (with L{restore()}).
2416+
2417+ Also check the MockerTestCase class, which integrates the
2418+ unittest.TestCase class with mocker.
2419+ """
2420+ if not self._recording:
2421+ for event in self._events:
2422+ event.restore()
2423+ else:
2424+ self._recording = False
2425+ for event in self._events:
2426+ event.replay()
2427+
2428+ def restore(self):
2429+ """Restore changes in the environment, and return to recording mode.
2430+
2431+ This should always be called after the test is complete (succeeding
2432+ or not). There are ways to call this method automatically on
2433+ completion (e.g. using a C{with mocker:} statement, or using the
2434+ L{MockerTestCase} class.
2435+ """
2436+ if not self._recording:
2437+ self._recording = True
2438+ for event in self._events:
2439+ event.restore()
2440+
2441+ def reset(self):
2442+ """Reset the mocker state.
2443+
2444+ This will restore environment changes, if currently in replay
2445+ mode, and then remove all events previously recorded.
2446+ """
2447+ if not self._recording:
2448+ self.restore()
2449+ self.unorder()
2450+ del self._events[:]
2451+
2452+ def get_events(self):
2453+ """Return all recorded events."""
2454+ return self._events[:]
2455+
2456+ def add_event(self, event):
2457+ """Add an event.
2458+
2459+ This method is used internally by the implementation, and
2460+ shouldn't be needed on normal mocker usage.
2461+ """
2462+ self._events.append(event)
2463+ if self._ordering:
2464+ orderer = event.add_task(Orderer(event.path))
2465+ if self._last_orderer:
2466+ orderer.add_dependency(self._last_orderer)
2467+ self._last_orderer = orderer
2468+ return event
2469+
2470+ def verify(self):
2471+ """Check if all expectations were met, and raise AssertionError if not.
2472+
2473+ The exception message will include a nice description of which
2474+ expectations were not met, and why.
2475+ """
2476+ errors = []
2477+ for event in self._events:
2478+ try:
2479+ event.verify()
2480+ except AssertionError, e:
2481+ error = str(e)
2482+ if not error:
2483+ raise RuntimeError("Empty error message from %r"
2484+ % event)
2485+ errors.append(error)
2486+ if errors:
2487+ message = [ERROR_PREFIX + "Unmet expectations:", ""]
2488+ for error in errors:
2489+ lines = error.splitlines()
2490+ message.append("=> " + lines.pop(0))
2491+ message.extend([" " + line for line in lines])
2492+ message.append("")
2493+ raise AssertionError(os.linesep.join(message))
2494+
2495+ def mock(self, spec_and_type=None, spec=None, type=None,
2496+ name=None, count=True):
2497+ """Return a new mock object.
2498+
2499+ @param spec_and_type: Handy positional argument which sets both
2500+ spec and type.
2501+ @param spec: Method calls will be checked for correctness against
2502+ the given class.
2503+ @param type: If set, the Mock's __class__ attribute will return
2504+ the given type. This will make C{isinstance()} calls
2505+ on the object work.
2506+ @param name: Name for the mock object, used in the representation of
2507+ expressions. The name is rarely needed, as it's usually
2508+ guessed correctly from the variable name used.
2509+ @param count: If set to false, expressions may be executed any number
2510+ of times, unless an expectation is explicitly set using
2511+ the L{count()} method. By default, expressions are
2512+ expected once.
2513+ """
2514+ if spec_and_type is not None:
2515+ spec = type = spec_and_type
2516+ return Mock(self, spec=spec, type=type, name=name, count=count)
2517+
2518+ def proxy(self, object, spec=True, type=True, name=None, count=True,
2519+ passthrough=True):
2520+ """Return a new mock object which proxies to the given object.
2521+
2522+ Proxies are useful when only part of the behavior of an object
2523+ is to be mocked. Unknown expressions may be passed through to
2524+ the real implementation implicitly (if the C{passthrough} argument
2525+ is True), or explicitly (using the L{passthrough()} method
2526+ on the event).
2527+
2528+ @param object: Real object to be proxied, and replaced by the mock
2529+ on replay mode. It may also be an "import path",
2530+ such as C{"time.time"}, in which case the object
2531+ will be the C{time} function from the C{time} module.
2532+ @param spec: Method calls will be checked for correctness against
2533+ the given object, which may be a class or an instance
2534+ where attributes will be looked up. Defaults to the
2535+ the C{object} parameter. May be set to None explicitly,
2536+ in which case spec checking is disabled. Checks may
2537+ also be disabled explicitly on a per-event basis with
2538+ the L{nospec()} method.
2539+ @param type: If set, the Mock's __class__ attribute will return
2540+ the given type. This will make C{isinstance()} calls
2541+ on the object work. Defaults to the type of the
2542+ C{object} parameter. May be set to None explicitly.
2543+ @param name: Name for the mock object, used in the representation of
2544+ expressions. The name is rarely needed, as it's usually
2545+ guessed correctly from the variable name used.
2546+ @param count: If set to false, expressions may be executed any number
2547+ of times, unless an expectation is explicitly set using
2548+ the L{count()} method. By default, expressions are
2549+ expected once.
2550+ @param passthrough: If set to False, passthrough of actions on the
2551+ proxy to the real object will only happen when
2552+ explicitly requested via the L{passthrough()}
2553+ method.
2554+ """
2555+ if isinstance(object, basestring):
2556+ if name is None:
2557+ name = object
2558+ import_stack = object.split(".")
2559+ attr_stack = []
2560+ while import_stack:
2561+ module_path = ".".join(import_stack)
2562+ try:
2563+ object = __import__(module_path, {}, {}, [""])
2564+ except ImportError:
2565+ attr_stack.insert(0, import_stack.pop())
2566+ if not import_stack:
2567+ raise
2568+ continue
2569+ else:
2570+ for attr in attr_stack:
2571+ object = getattr(object, attr)
2572+ break
2573+ if spec is True:
2574+ spec = object
2575+ if type is True:
2576+ type = __builtin__.type(object)
2577+ return Mock(self, spec=spec, type=type, object=object,
2578+ name=name, count=count, passthrough=passthrough)
2579+
2580+ def replace(self, object, spec=True, type=True, name=None, count=True,
2581+ passthrough=True):
2582+ """Create a proxy, and replace the original object with the mock.
2583+
2584+ On replay, the original object will be replaced by the returned
2585+ proxy in all dictionaries found in the running interpreter via
2586+ the garbage collecting system. This should cover module
2587+ namespaces, class namespaces, instance namespaces, and so on.
2588+
2589+ @param object: Real object to be proxied, and replaced by the mock
2590+ on replay mode. It may also be an "import path",
2591+ such as C{"time.time"}, in which case the object
2592+ will be the C{time} function from the C{time} module.
2593+ @param spec: Method calls will be checked for correctness against
2594+ the given object, which may be a class or an instance
2595+ where attributes will be looked up. Defaults to the
2596+ the C{object} parameter. May be set to None explicitly,
2597+ in which case spec checking is disabled. Checks may
2598+ also be disabled explicitly on a per-event basis with
2599+ the L{nospec()} method.
2600+ @param type: If set, the Mock's __class__ attribute will return
2601+ the given type. This will make C{isinstance()} calls
2602+ on the object work. Defaults to the type of the
2603+ C{object} parameter. May be set to None explicitly.
2604+ @param name: Name for the mock object, used in the representation of
2605+ expressions. The name is rarely needed, as it's usually
2606+ guessed correctly from the variable name used.
2607+ @param passthrough: If set to False, passthrough of actions on the
2608+ proxy to the real object will only happen when
2609+ explicitly requested via the L{passthrough()}
2610+ method.
2611+ """
2612+ mock = self.proxy(object, spec, type, name, count, passthrough)
2613+ event = self._get_replay_restore_event()
2614+ event.add_task(ProxyReplacer(mock))
2615+ return mock
2616+
2617+ def patch(self, object, spec=True):
2618+ """Patch an existing object to reproduce recorded events.
2619+
2620+ @param object: Class or instance to be patched.
2621+ @param spec: Method calls will be checked for correctness against
2622+ the given object, which may be a class or an instance
2623+ where attributes will be looked up. Defaults to the
2624+ the C{object} parameter. May be set to None explicitly,
2625+ in which case spec checking is disabled. Checks may
2626+ also be disabled explicitly on a per-event basis with
2627+ the L{nospec()} method.
2628+
2629+ The result of this method is still a mock object, which can be
2630+ used like any other mock object to record events. The difference
2631+ is that when the mocker is put on replay mode, the *real* object
2632+ will be modified to behave according to recorded expectations.
2633+
2634+ Patching works in individual instances, and also in classes.
2635+ When an instance is patched, recorded events will only be
2636+ considered on this specific instance, and other instances should
2637+ behave normally. When a class is patched, the reproduction of
2638+ events will be considered on any instance of this class once
2639+ created (collectively).
2640+
2641+ Observe that, unlike with proxies which catch only events done
2642+ through the mock object, *all* accesses to recorded expectations
2643+ will be considered; even these coming from the object itself
2644+ (e.g. C{self.hello()} is considered if this method was patched).
2645+ While this is a very powerful feature, and many times the reason
2646+ to use patches in the first place, it's important to keep this
2647+ behavior in mind.
2648+
2649+ Patching of the original object only takes place when the mocker
2650+ is put on replay mode, and the patched object will be restored
2651+ to its original state once the L{restore()} method is called
2652+ (explicitly, or implicitly with alternative conventions, such as
2653+ a C{with mocker:} block, or a MockerTestCase class).
2654+ """
2655+ if spec is True:
2656+ spec = object
2657+ patcher = Patcher()
2658+ event = self._get_replay_restore_event()
2659+ event.add_task(patcher)
2660+ mock = Mock(self, object=object, patcher=patcher,
2661+ passthrough=True, spec=spec)
2662+ object.__mocker_mock__ = mock
2663+ return mock
2664+
2665+ def act(self, path):
2666+ """This is called by mock objects whenever something happens to them.
2667+
2668+ This method is part of the implementation between the mocker
2669+ and mock objects.
2670+ """
2671+ if self._recording:
2672+ event = self.add_event(Event(path))
2673+ for recorder in self._recorders:
2674+ recorder(self, event)
2675+ return Mock(self, path)
2676+ else:
2677+ # First run events that may run, then run unsatisfied events, then
2678+ # ones not previously run. We put the index in the ordering tuple
2679+ # instead of the actual event because we want a stable sort
2680+ # (ordering between 2 events is undefined).
2681+ events = self._events
2682+ order = [(events[i].satisfied()*2 + events[i].has_run(), i)
2683+ for i in range(len(events))]
2684+ order.sort()
2685+ postponed = None
2686+ for weight, i in order:
2687+ event = events[i]
2688+ if event.matches(path):
2689+ if event.may_run(path):
2690+ return event.run(path)
2691+ elif postponed is None:
2692+ postponed = event
2693+ if postponed is not None:
2694+ return postponed.run(path)
2695+ raise MatchError(ERROR_PREFIX + "Unexpected expression: %s" % path)
2696+
2697+ def get_recorders(cls, self):
2698+ """Return recorders associated with this mocker class or instance.
2699+
2700+ This method may be called on mocker instances and also on mocker
2701+ classes. See the L{add_recorder()} method for more information.
2702+ """
2703+ return (self or cls)._recorders[:]
2704+ get_recorders = classinstancemethod(get_recorders)
2705+
2706+ def add_recorder(cls, self, recorder):
2707+ """Add a recorder to this mocker class or instance.
2708+
2709+ @param recorder: Callable accepting C{(mocker, event)} as parameters.
2710+
2711+ This is part of the implementation of mocker.
2712+
2713+ All registered recorders are called for translating events that
2714+ happen during recording into expectations to be met once the state
2715+ is switched to replay mode.
2716+
2717+ This method may be called on mocker instances and also on mocker
2718+ classes. When called on a class, the recorder will be used by
2719+ all instances, and also inherited on subclassing. When called on
2720+ instances, the recorder is added only to the given instance.
2721+ """
2722+ (self or cls)._recorders.append(recorder)
2723+ return recorder
2724+ add_recorder = classinstancemethod(add_recorder)
2725+
2726+ def remove_recorder(cls, self, recorder):
2727+ """Remove the given recorder from this mocker class or instance.
2728+
2729+ This method may be called on mocker classes and also on mocker
2730+ instances. See the L{add_recorder()} method for more information.
2731+ """
2732+ (self or cls)._recorders.remove(recorder)
2733+ remove_recorder = classinstancemethod(remove_recorder)
2734+
2735+ def result(self, value):
2736+ """Make the last recorded event return the given value on replay.
2737+
2738+ @param value: Object to be returned when the event is replayed.
2739+ """
2740+ self.call(lambda *args, **kwargs: value)
2741+
2742+ def generate(self, sequence):
2743+ """Last recorded event will return a generator with the given sequence.
2744+
2745+ @param sequence: Sequence of values to be generated.
2746+ """
2747+ def generate(*args, **kwargs):
2748+ for value in sequence:
2749+ yield value
2750+ self.call(generate)
2751+
2752+ def throw(self, exception):
2753+ """Make the last recorded event raise the given exception on replay.
2754+
2755+ @param exception: Class or instance of exception to be raised.
2756+ """
2757+ def raise_exception(*args, **kwargs):
2758+ raise exception
2759+ self.call(raise_exception)
2760+
2761+ def call(self, func):
2762+ """Make the last recorded event cause the given function to be called.
2763+
2764+ @param func: Function to be called.
2765+
2766+ The result of the function will be used as the event result.
2767+ """
2768+ self._events[-1].add_task(FunctionRunner(func))
2769+
2770+ def count(self, min, max=False):
2771+ """Last recorded event must be replayed between min and max times.
2772+
2773+ @param min: Minimum number of times that the event must happen.
2774+ @param max: Maximum number of times that the event must happen. If
2775+ not given, it defaults to the same value of the C{min}
2776+ parameter. If set to None, there is no upper limit, and
2777+ the expectation is met as long as it happens at least
2778+ C{min} times.
2779+ """
2780+ event = self._events[-1]
2781+ for task in event.get_tasks():
2782+ if isinstance(task, RunCounter):
2783+ event.remove_task(task)
2784+ event.add_task(RunCounter(min, max))
2785+
2786+ def is_ordering(self):
2787+ """Return true if all events are being ordered.
2788+
2789+ See the L{order()} method.
2790+ """
2791+ return self._ordering
2792+
2793+ def unorder(self):
2794+ """Disable the ordered mode.
2795+
2796+ See the L{order()} method for more information.
2797+ """
2798+ self._ordering = False
2799+ self._last_orderer = None
2800+
2801+ def order(self, *path_holders):
2802+ """Create an expectation of order between two or more events.
2803+
2804+ @param path_holders: Objects returned as the result of recorded events.
2805+
2806+ By default, mocker won't force events to happen precisely in
2807+ the order they were recorded. Calling this method will change
2808+ this behavior so that events will only match if reproduced in
2809+ the correct order.
2810+
2811+ There are two ways in which this method may be used. Which one
2812+ is used in a given occasion depends only on convenience.
2813+
2814+ If no arguments are passed, the mocker will be put in a mode where
2815+ all the recorded events following the method call will only be met
2816+ if they happen in order. When that's used, the mocker may be put
2817+ back in unordered mode by calling the L{unorder()} method, or by
2818+ using a 'with' block, like so::
2819+
2820+ with mocker.ordered():
2821+ <record events>
2822+
2823+ In this case, only expressions in <record events> will be ordered,
2824+ and the mocker will be back in unordered mode after the 'with' block.
2825+
2826+ The second way to use it is by specifying precisely which events
2827+ should be ordered. As an example::
2828+
2829+ mock = mocker.mock()
2830+ expr1 = mock.hello()
2831+ expr2 = mock.world
2832+ expr3 = mock.x.y.z
2833+ mocker.order(expr1, expr2, expr3)
2834+
2835+ This method of ordering only works when the expression returns
2836+ another object.
2837+
2838+ Also check the L{after()} and L{before()} methods, which are
2839+ alternative ways to perform this.
2840+ """
2841+ if not path_holders:
2842+ self._ordering = True
2843+ return OrderedContext(self)
2844+
2845+ last_orderer = None
2846+ for path_holder in path_holders:
2847+ if type(path_holder) is Path:
2848+ path = path_holder
2849+ else:
2850+ path = path_holder.__mocker_path__
2851+ for event in self._events:
2852+ if event.path is path:
2853+ for task in event.get_tasks():
2854+ if isinstance(task, Orderer):
2855+ orderer = task
2856+ break
2857+ else:
2858+ orderer = Orderer(path)
2859+ event.add_task(orderer)
2860+ if last_orderer:
2861+ orderer.add_dependency(last_orderer)
2862+ last_orderer = orderer
2863+ break
2864+
2865+ def after(self, *path_holders):
2866+ """Last recorded event must happen after events referred to.
2867+
2868+ @param path_holders: Objects returned as the result of recorded events
2869+ which should happen before the last recorded event
2870+
2871+ As an example, the idiom::
2872+
2873+ expect(mock.x).after(mock.y, mock.z)
2874+
2875+ is an alternative way to say::
2876+
2877+ expr_x = mock.x
2878+ expr_y = mock.y
2879+ expr_z = mock.z
2880+ mocker.order(expr_y, expr_x)
2881+ mocker.order(expr_z, expr_x)
2882+
2883+ See L{order()} for more information.
2884+ """
2885+ last_path = self._events[-1].path
2886+ for path_holder in path_holders:
2887+ self.order(path_holder, last_path)
2888+
2889+ def before(self, *path_holders):
2890+ """Last recorded event must happen before events referred to.
2891+
2892+ @param path_holders: Objects returned as the result of recorded events
2893+ which should happen after the last recorded event
2894+
2895+ As an example, the idiom::
2896+
2897+ expect(mock.x).before(mock.y, mock.z)
2898+
2899+ is an alternative way to say::
2900+
2901+ expr_x = mock.x
2902+ expr_y = mock.y
2903+ expr_z = mock.z
2904+ mocker.order(expr_x, expr_y)
2905+ mocker.order(expr_x, expr_z)
2906+
2907+ See L{order()} for more information.
2908+ """
2909+ last_path = self._events[-1].path
2910+ for path_holder in path_holders:
2911+ self.order(last_path, path_holder)
2912+
2913+ def nospec(self):
2914+ """Don't check method specification of real object on last event.
2915+
2916+ By default, when using a mock created as the result of a call to
2917+ L{proxy()}, L{replace()}, and C{patch()}, or when passing the spec
2918+ attribute to the L{mock()} method, method calls on the given object
2919+ are checked for correctness against the specification of the real
2920+ object (or the explicitly provided spec).
2921+
2922+ This method will disable that check specifically for the last
2923+ recorded event.
2924+ """
2925+ event = self._events[-1]
2926+ for task in event.get_tasks():
2927+ if isinstance(task, SpecChecker):
2928+ event.remove_task(task)
2929+
2930+ def passthrough(self, result_callback=None):
2931+ """Make the last recorded event run on the real object once seen.
2932+
2933+ @param result_callback: If given, this function will be called with
2934+ the result of the *real* method call as the only argument.
2935+
2936+ This can only be used on proxies, as returned by the L{proxy()}
2937+ and L{replace()} methods, or on mocks representing patched objects,
2938+ as returned by the L{patch()} method.
2939+ """
2940+ event = self._events[-1]
2941+ if event.path.root_object is None:
2942+ raise TypeError("Mock object isn't a proxy")
2943+ event.add_task(PathExecuter(result_callback))
2944+
2945+ def __enter__(self):
2946+ """Enter in a 'with' context. This will run replay()."""
2947+ self.replay()
2948+ return self
2949+
2950+ def __exit__(self, type, value, traceback):
2951+ """Exit from a 'with' context.
2952+
2953+ This will run restore() at all times, but will only run verify()
2954+ if the 'with' block itself hasn't raised an exception. Exceptions
2955+ in that block are never swallowed.
2956+ """
2957+ self.restore()
2958+ if type is None:
2959+ self.verify()
2960+ return False
2961+
2962+ def _get_replay_restore_event(self):
2963+ """Return unique L{ReplayRestoreEvent}, creating if needed.
2964+
2965+ Some tasks only want to replay/restore. When that's the case,
2966+ they shouldn't act on other events during replay. Also, they
2967+ can all be put in a single event when that's the case. Thus,
2968+ we add a single L{ReplayRestoreEvent} as the first element of
2969+ the list.
2970+ """
2971+ if not self._events or type(self._events[0]) != ReplayRestoreEvent:
2972+ self._events.insert(0, ReplayRestoreEvent())
2973+ return self._events[0]
2974+
2975+
2976+class OrderedContext(object):
2977+
2978+ def __init__(self, mocker):
2979+ self._mocker = mocker
2980+
2981+ def __enter__(self):
2982+ return None
2983+
2984+ def __exit__(self, type, value, traceback):
2985+ self._mocker.unorder()
2986+
2987+
2988+class Mocker(MockerBase):
2989+ __doc__ = MockerBase.__doc__
2990+
2991+# Decorator to add recorders on the standard Mocker class.
2992+recorder = Mocker.add_recorder
2993+
2994+
2995+# --------------------------------------------------------------------
2996+# Mock object.
2997+
2998+class Mock(object):
2999+
3000+ def __init__(self, mocker, path=None, name=None, spec=None, type=None,
3001+ object=None, passthrough=False, patcher=None, count=True):
3002+ self.__mocker__ = mocker
3003+ self.__mocker_path__ = path or Path(self, object)
3004+ self.__mocker_name__ = name
3005+ self.__mocker_spec__ = spec
3006+ self.__mocker_object__ = object
3007+ self.__mocker_passthrough__ = passthrough
3008+ self.__mocker_patcher__ = patcher
3009+ self.__mocker_replace__ = False
3010+ self.__mocker_type__ = type
3011+ self.__mocker_count__ = count
3012+
3013+ def __mocker_act__(self, kind, args=(), kwargs={}, object=None):
3014+ if self.__mocker_name__ is None:
3015+ self.__mocker_name__ = find_object_name(self, 2)
3016+ action = Action(kind, args, kwargs, self.__mocker_path__)
3017+ path = self.__mocker_path__ + action
3018+ if object is not None:
3019+ path.root_object = object
3020+ try:
3021+ return self.__mocker__.act(path)
3022+ except MatchError, exception:
3023+ root_mock = path.root_mock
3024+ if (path.root_object is not None and
3025+ root_mock.__mocker_passthrough__):
3026+ return path.execute(path.root_object)
3027+ # Reinstantiate to show raise statement on traceback, and
3028+ # also to make the traceback shown shorter.
3029+ raise MatchError(str(exception))
3030+ except AssertionError, e:
3031+ lines = str(e).splitlines()
3032+ message = [ERROR_PREFIX + "Unmet expectation:", ""]
3033+ message.append("=> " + lines.pop(0))
3034+ message.extend([" " + line for line in lines])
3035+ message.append("")
3036+ raise AssertionError(os.linesep.join(message))
3037+
3038+ def __getattribute__(self, name):
3039+ if name.startswith("__mocker_"):
3040+ return super(Mock, self).__getattribute__(name)
3041+ if name == "__class__":
3042+ if self.__mocker__.is_recording() or self.__mocker_type__ is None:
3043+ return type(self)
3044+ return self.__mocker_type__
3045+ return self.__mocker_act__("getattr", (name,))
3046+
3047+ def __setattr__(self, name, value):
3048+ if name.startswith("__mocker_"):
3049+ return super(Mock, self).__setattr__(name, value)
3050+ return self.__mocker_act__("setattr", (name, value))
3051+
3052+ def __delattr__(self, name):
3053+ return self.__mocker_act__("delattr", (name,))
3054+
3055+ def __call__(self, *args, **kwargs):
3056+ return self.__mocker_act__("call", args, kwargs)
3057+
3058+ def __contains__(self, value):
3059+ return self.__mocker_act__("contains", (value,))
3060+
3061+ def __getitem__(self, key):
3062+ return self.__mocker_act__("getitem", (key,))
3063+
3064+ def __setitem__(self, key, value):
3065+ return self.__mocker_act__("setitem", (key, value))
3066+
3067+ def __delitem__(self, key):
3068+ return self.__mocker_act__("delitem", (key,))
3069+
3070+ def __len__(self):
3071+ # MatchError is turned on an AttributeError so that list() and
3072+ # friends act properly when trying to get length hints on
3073+ # something that doesn't offer them.
3074+ try:
3075+ result = self.__mocker_act__("len")
3076+ except MatchError, e:
3077+ raise AttributeError(str(e))
3078+ if type(result) is Mock:
3079+ return 0
3080+ return result
3081+
3082+ def __nonzero__(self):
3083+ try:
3084+ return self.__mocker_act__("nonzero")
3085+ except MatchError, e:
3086+ return True
3087+
3088+ def __iter__(self):
3089+ # XXX On py3k, when next() becomes __next__(), we'll be able
3090+ # to return the mock itself because it will be considered
3091+ # an iterator (we'll be mocking __next__ as well, which we
3092+ # can't now).
3093+ result = self.__mocker_act__("iter")
3094+ if type(result) is Mock:
3095+ return iter([])
3096+ return result
3097+
3098+ # When adding a new action kind here, also add support for it on
3099+ # Action.execute() and Path.__str__().
3100+
3101+
3102+def find_object_name(obj, depth=0):
3103+ """Try to detect how the object is named on a previous scope."""
3104+ try:
3105+ frame = sys._getframe(depth+1)
3106+ except:
3107+ return None
3108+ for name, frame_obj in frame.f_locals.iteritems():
3109+ if frame_obj is obj:
3110+ return name
3111+ self = frame.f_locals.get("self")
3112+ if self is not None:
3113+ try:
3114+ items = list(self.__dict__.iteritems())
3115+ except:
3116+ pass
3117+ else:
3118+ for name, self_obj in items:
3119+ if self_obj is obj:
3120+ return name
3121+ return None
3122+
3123+
3124+# --------------------------------------------------------------------
3125+# Action and path.
3126+
3127+class Action(object):
3128+
3129+ def __init__(self, kind, args, kwargs, path=None):
3130+ self.kind = kind
3131+ self.args = args
3132+ self.kwargs = kwargs
3133+ self.path = path
3134+ self._execute_cache = {}
3135+
3136+ def __repr__(self):
3137+ if self.path is None:
3138+ return "Action(%r, %r, %r)" % (self.kind, self.args, self.kwargs)
3139+ return "Action(%r, %r, %r, %r)" % \
3140+ (self.kind, self.args, self.kwargs, self.path)
3141+
3142+ def __eq__(self, other):
3143+ return (self.kind == other.kind and
3144+ self.args == other.args and
3145+ self.kwargs == other.kwargs)
3146+
3147+ def __ne__(self, other):
3148+ return not self.__eq__(other)
3149+
3150+ def matches(self, other):
3151+ return (self.kind == other.kind and
3152+ match_params(self.args, self.kwargs, other.args, other.kwargs))
3153+
3154+ def execute(self, object):
3155+ # This caching scheme may fail if the object gets deallocated before
3156+ # the action, as the id might get reused. It's somewhat easy to fix
3157+ # that with a weakref callback. For our uses, though, the object
3158+ # should never get deallocated before the action itself, so we'll
3159+ # just keep it simple.
3160+ if id(object) in self._execute_cache:
3161+ return self._execute_cache[id(object)]
3162+ execute = getattr(object, "__mocker_execute__", None)
3163+ if execute is not None:
3164+ result = execute(self, object)
3165+ else:
3166+ kind = self.kind
3167+ if kind == "getattr":
3168+ result = getattr(object, self.args[0])
3169+ elif kind == "setattr":
3170+ result = setattr(object, self.args[0], self.args[1])
3171+ elif kind == "delattr":
3172+ result = delattr(object, self.args[0])
3173+ elif kind == "call":
3174+ result = object(*self.args, **self.kwargs)
3175+ elif kind == "contains":
3176+ result = self.args[0] in object
3177+ elif kind == "getitem":
3178+ result = object[self.args[0]]
3179+ elif kind == "setitem":
3180+ result = object[self.args[0]] = self.args[1]
3181+ elif kind == "delitem":
3182+ del object[self.args[0]]
3183+ result = None
3184+ elif kind == "len":
3185+ result = len(object)
3186+ elif kind == "nonzero":
3187+ result = bool(object)
3188+ elif kind == "iter":
3189+ result = iter(object)
3190+ else:
3191+ raise RuntimeError("Don't know how to execute %r kind." % kind)
3192+ self._execute_cache[id(object)] = result
3193+ return result
3194+
3195+
3196+class Path(object):
3197+
3198+ def __init__(self, root_mock, root_object=None, actions=()):
3199+ self.root_mock = root_mock
3200+ self.root_object = root_object
3201+ self.actions = tuple(actions)
3202+ self.__mocker_replace__ = False
3203+
3204+ def parent_path(self):
3205+ if not self.actions:
3206+ return None
3207+ return self.actions[-1].path
3208+ parent_path = property(parent_path)
3209+
3210+ def __add__(self, action):
3211+ """Return a new path which includes the given action at the end."""
3212+ return self.__class__(self.root_mock, self.root_object,
3213+ self.actions + (action,))
3214+
3215+ def __eq__(self, other):
3216+ """Verify if the two paths are equal.
3217+
3218+ Two paths are equal if they refer to the same mock object, and
3219+ have the actions with equal kind, args and kwargs.
3220+ """
3221+ if (self.root_mock is not other.root_mock or
3222+ self.root_object is not other.root_object or
3223+ len(self.actions) != len(other.actions)):
3224+ return False
3225+ for action, other_action in zip(self.actions, other.actions):
3226+ if action != other_action:
3227+ return False
3228+ return True
3229+
3230+ def matches(self, other):
3231+ """Verify if the two paths are equivalent.
3232+
3233+ Two paths are equal if they refer to the same mock object, and
3234+ have the same actions performed on them.
3235+ """
3236+ if (self.root_mock is not other.root_mock or
3237+ len(self.actions) != len(other.actions)):
3238+ return False
3239+ for action, other_action in zip(self.actions, other.actions):
3240+ if not action.matches(other_action):
3241+ return False
3242+ return True
3243+
3244+ def execute(self, object):
3245+ """Execute all actions sequentially on object, and return result.
3246+ """
3247+ for action in self.actions:
3248+ object = action.execute(object)
3249+ return object
3250+
3251+ def __str__(self):
3252+ """Transform the path into a nice string such as obj.x.y('z')."""
3253+ result = self.root_mock.__mocker_name__ or "<mock>"
3254+ for action in self.actions:
3255+ if action.kind == "getattr":
3256+ result = "%s.%s" % (result, action.args[0])
3257+ elif action.kind == "setattr":
3258+ result = "%s.%s = %r" % (result, action.args[0], action.args[1])
3259+ elif action.kind == "delattr":
3260+ result = "del %s.%s" % (result, action.args[0])
3261+ elif action.kind == "call":
3262+ args = [repr(x) for x in action.args]
3263+ items = list(action.kwargs.iteritems())
3264+ items.sort()
3265+ for pair in items:
3266+ args.append("%s=%r" % pair)
3267+ result = "%s(%s)" % (result, ", ".join(args))
3268+ elif action.kind == "contains":
3269+ result = "%r in %s" % (action.args[0], result)
3270+ elif action.kind == "getitem":
3271+ result = "%s[%r]" % (result, action.args[0])
3272+ elif action.kind == "setitem":
3273+ result = "%s[%r] = %r" % (result, action.args[0],
3274+ action.args[1])
3275+ elif action.kind == "delitem":
3276+ result = "del %s[%r]" % (result, action.args[0])
3277+ elif action.kind == "len":
3278+ result = "len(%s)" % result
3279+ elif action.kind == "nonzero":
3280+ result = "bool(%s)" % result
3281+ elif action.kind == "iter":
3282+ result = "iter(%s)" % result
3283+ else:
3284+ raise RuntimeError("Don't know how to format kind %r" %
3285+ action.kind)
3286+ return result
3287+
3288+
3289+class SpecialArgument(object):
3290+ """Base for special arguments for matching parameters."""
3291+
3292+ def __init__(self, object=None):
3293+ self.object = object
3294+
3295+ def __repr__(self):
3296+ if self.object is None:
3297+ return self.__class__.__name__
3298+ else:
3299+ return "%s(%r)" % (self.__class__.__name__, self.object)
3300+
3301+ def matches(self, other):
3302+ return True
3303+
3304+ def __eq__(self, other):
3305+ return type(other) == type(self) and self.object == other.object
3306+
3307+
3308+class ANY(SpecialArgument):
3309+ """Matches any single argument."""
3310+
3311+ANY = ANY()
3312+
3313+
3314+class ARGS(SpecialArgument):
3315+ """Matches zero or more positional arguments."""
3316+
3317+ARGS = ARGS()
3318+
3319+
3320+class KWARGS(SpecialArgument):
3321+ """Matches zero or more keyword arguments."""
3322+
3323+KWARGS = KWARGS()
3324+
3325+
3326+class IS(SpecialArgument):
3327+
3328+ def matches(self, other):
3329+ return self.object is other
3330+
3331+ def __eq__(self, other):
3332+ return type(other) == type(self) and self.object is other.object
3333+
3334+
3335+class CONTAINS(SpecialArgument):
3336+
3337+ def matches(self, other):
3338+ try:
3339+ other.__contains__
3340+ except AttributeError:
3341+ try:
3342+ iter(other)
3343+ except TypeError:
3344+ # If an object can't be iterated, and has no __contains__
3345+ # hook, it'd blow up on the test below. We test this in
3346+ # advance to prevent catching more errors than we really
3347+ # want.
3348+ return False
3349+ return self.object in other
3350+
3351+
3352+class IN(SpecialArgument):
3353+
3354+ def matches(self, other):
3355+ return other in self.object
3356+
3357+
3358+class MATCH(SpecialArgument):
3359+
3360+ def matches(self, other):
3361+ return bool(self.object(other))
3362+
3363+ def __eq__(self, other):
3364+ return type(other) == type(self) and self.object is other.object
3365+
3366+
3367+def match_params(args1, kwargs1, args2, kwargs2):
3368+ """Match the two sets of parameters, considering special parameters."""
3369+
3370+ has_args = ARGS in args1
3371+ has_kwargs = KWARGS in args1
3372+
3373+ if has_kwargs:
3374+ args1 = [arg1 for arg1 in args1 if arg1 is not KWARGS]
3375+ elif len(kwargs1) != len(kwargs2):
3376+ return False
3377+
3378+ if not has_args and len(args1) != len(args2):
3379+ return False
3380+
3381+ # Either we have the same number of kwargs, or unknown keywords are
3382+ # accepted (KWARGS was used), so check just the ones in kwargs1.
3383+ for key, arg1 in kwargs1.iteritems():
3384+ if key not in kwargs2:
3385+ return False
3386+ arg2 = kwargs2[key]
3387+ if isinstance(arg1, SpecialArgument):
3388+ if not arg1.matches(arg2):
3389+ return False
3390+ elif arg1 != arg2:
3391+ return False
3392+
3393+ # Keywords match. Now either we have the same number of
3394+ # arguments, or ARGS was used. If ARGS wasn't used, arguments
3395+ # must match one-on-one necessarily.
3396+ if not has_args:
3397+ for arg1, arg2 in zip(args1, args2):
3398+ if isinstance(arg1, SpecialArgument):
3399+ if not arg1.matches(arg2):
3400+ return False
3401+ elif arg1 != arg2:
3402+ return False
3403+ return True
3404+
3405+ # Easy choice. Keywords are matching, and anything on args is accepted.
3406+ if (ARGS,) == args1:
3407+ return True
3408+
3409+ # We have something different there. If we don't have positional
3410+ # arguments on the original call, it can't match.
3411+ if not args2:
3412+ # Unless we have just several ARGS (which is bizarre, but..).
3413+ for arg1 in args1:
3414+ if arg1 is not ARGS:
3415+ return False
3416+ return True
3417+
3418+ # Ok, all bets are lost. We have to actually do the more expensive
3419+ # matching. This is an algorithm based on the idea of the Levenshtein
3420+ # Distance between two strings, but heavily hacked for this purpose.
3421+ args2l = len(args2)
3422+ if args1[0] is ARGS:
3423+ args1 = args1[1:]
3424+ array = [0]*args2l
3425+ else:
3426+ array = [1]*args2l
3427+ for i in range(len(args1)):
3428+ last = array[0]
3429+ if args1[i] is ARGS:
3430+ for j in range(1, args2l):
3431+ last, array[j] = array[j], min(array[j-1], array[j], last)
3432+ else:
3433+ array[0] = i or int(args1[i] != args2[0])
3434+ for j in range(1, args2l):
3435+ last, array[j] = array[j], last or int(args1[i] != args2[j])
3436+ if 0 not in array:
3437+ return False
3438+ if array[-1] != 0:
3439+ return False
3440+ return True
3441+
3442+
3443+# --------------------------------------------------------------------
3444+# Event and task base.
3445+
3446+class Event(object):
3447+ """Aggregation of tasks that keep track of a recorded action.
3448+
3449+ An event represents something that may or may not happen while the
3450+ mocked environment is running, such as an attribute access, or a
3451+ method call. The event is composed of several tasks that are
3452+ orchestrated together to create a composed meaning for the event,
3453+ including for which actions it should be run, what happens when it
3454+ runs, and what's the expectations about the actions run.
3455+ """
3456+
3457+ def __init__(self, path=None):
3458+ self.path = path
3459+ self._tasks = []
3460+ self._has_run = False
3461+
3462+ def add_task(self, task):
3463+ """Add a new task to this taks."""
3464+ self._tasks.append(task)
3465+ return task
3466+
3467+ def remove_task(self, task):
3468+ self._tasks.remove(task)
3469+
3470+ def get_tasks(self):
3471+ return self._tasks[:]
3472+
3473+ def matches(self, path):
3474+ """Return true if *all* tasks match the given path."""
3475+ for task in self._tasks:
3476+ if not task.matches(path):
3477+ return False
3478+ return bool(self._tasks)
3479+
3480+ def has_run(self):
3481+ return self._has_run
3482+
3483+ def may_run(self, path):
3484+ """Verify if any task would certainly raise an error if run.
3485+
3486+ This will call the C{may_run()} method on each task and return
3487+ false if any of them returns false.
3488+ """
3489+ for task in self._tasks:
3490+ if not task.may_run(path):
3491+ return False
3492+ return True
3493+
3494+ def run(self, path):
3495+ """Run all tasks with the given action.
3496+
3497+ @param path: The path of the expression run.
3498+
3499+ Running an event means running all of its tasks individually and in
3500+ order. An event should only ever be run if all of its tasks claim to
3501+ match the given action.
3502+
3503+ The result of this method will be the last result of a task
3504+ which isn't None, or None if they're all None.
3505+ """
3506+ self._has_run = True
3507+ result = None
3508+ errors = []
3509+ for task in self._tasks:
3510+ try:
3511+ task_result = task.run(path)
3512+ except AssertionError, e:
3513+ error = str(e)
3514+ if not error:
3515+ raise RuntimeError("Empty error message from %r" % task)
3516+ errors.append(error)
3517+ else:
3518+ if task_result is not None:
3519+ result = task_result
3520+ if errors:
3521+ message = [str(self.path)]
3522+ if str(path) != message[0]:
3523+ message.append("- Run: %s" % path)
3524+ for error in errors:
3525+ lines = error.splitlines()
3526+ message.append("- " + lines.pop(0))
3527+ message.extend([" " + line for line in lines])
3528+ raise AssertionError(os.linesep.join(message))
3529+ return result
3530+
3531+ def satisfied(self):
3532+ """Return true if all tasks are satisfied.
3533+
3534+ Being satisfied means that there are no unmet expectations.
3535+ """
3536+ for task in self._tasks:
3537+ try:
3538+ task.verify()
3539+ except AssertionError:
3540+ return False
3541+ return True
3542+
3543+ def verify(self):
3544+ """Run verify on all tasks.
3545+
3546+ The verify method is supposed to raise an AssertionError if the
3547+ task has unmet expectations, with a one-line explanation about
3548+ why this item is unmet. This method should be safe to be called
3549+ multiple times without side effects.
3550+ """
3551+ errors = []
3552+ for task in self._tasks:
3553+ try:
3554+ task.verify()
3555+ except AssertionError, e:
3556+ error = str(e)
3557+ if not error:
3558+ raise RuntimeError("Empty error message from %r" % task)
3559+ errors.append(error)
3560+ if errors:
3561+ message = [str(self.path)]
3562+ for error in errors:
3563+ lines = error.splitlines()
3564+ message.append("- " + lines.pop(0))
3565+ message.extend([" " + line for line in lines])
3566+ raise AssertionError(os.linesep.join(message))
3567+
3568+ def replay(self):
3569+ """Put all tasks in replay mode."""
3570+ self._has_run = False
3571+ for task in self._tasks:
3572+ task.replay()
3573+
3574+ def restore(self):
3575+ """Restore the state of all tasks."""
3576+ for task in self._tasks:
3577+ task.restore()
3578+
3579+
3580+class ReplayRestoreEvent(Event):
3581+ """Helper event for tasks which need replay/restore but shouldn't match."""
3582+
3583+ def matches(self, path):
3584+ return False
3585+
3586+
3587+class Task(object):
3588+ """Element used to track one specific aspect on an event.
3589+
3590+ A task is responsible for adding any kind of logic to an event.
3591+ Examples of that are counting the number of times the event was
3592+ made, verifying parameters if any, and so on.
3593+ """
3594+
3595+ def matches(self, path):
3596+ """Return true if the task is supposed to be run for the given path.
3597+ """
3598+ return True
3599+
3600+ def may_run(self, path):
3601+ """Return false if running this task would certainly raise an error."""
3602+ return True
3603+
3604+ def run(self, path):
3605+ """Perform the task item, considering that the given action happened.
3606+ """
3607+
3608+ def verify(self):
3609+ """Raise AssertionError if expectations for this item are unmet.
3610+
3611+ The verify method is supposed to raise an AssertionError if the
3612+ task has unmet expectations, with a one-line explanation about
3613+ why this item is unmet. This method should be safe to be called
3614+ multiple times without side effects.
3615+ """
3616+
3617+ def replay(self):
3618+ """Put the task in replay mode.
3619+
3620+ Any expectations of the task should be reset.
3621+ """
3622+
3623+ def restore(self):
3624+ """Restore any environmental changes made by the task.
3625+
3626+ Verify should continue to work after this is called.
3627+ """
3628+
3629+
3630+# --------------------------------------------------------------------
3631+# Task implementations.
3632+
3633+class OnRestoreCaller(Task):
3634+ """Call a given callback when restoring."""
3635+
3636+ def __init__(self, callback):
3637+ self._callback = callback
3638+
3639+ def restore(self):
3640+ self._callback()
3641+
3642+
3643+class PathMatcher(Task):
3644+ """Match the action path against a given path."""
3645+
3646+ def __init__(self, path):
3647+ self.path = path
3648+
3649+ def matches(self, path):
3650+ return self.path.matches(path)
3651+
3652+def path_matcher_recorder(mocker, event):
3653+ event.add_task(PathMatcher(event.path))
3654+
3655+Mocker.add_recorder(path_matcher_recorder)
3656+
3657+
3658+class RunCounter(Task):
3659+ """Task which verifies if the number of runs are within given boundaries.
3660+ """
3661+
3662+ def __init__(self, min, max=False):
3663+ self.min = min
3664+ if max is None:
3665+ self.max = sys.maxint
3666+ elif max is False:
3667+ self.max = min
3668+ else:
3669+ self.max = max
3670+ self._runs = 0
3671+
3672+ def replay(self):
3673+ self._runs = 0
3674+
3675+ def may_run(self, path):
3676+ return self._runs < self.max
3677+
3678+ def run(self, path):
3679+ self._runs += 1
3680+ if self._runs > self.max:
3681+ self.verify()
3682+
3683+ def verify(self):
3684+ if not self.min <= self._runs <= self.max:
3685+ if self._runs < self.min:
3686+ raise AssertionError("Performed fewer times than expected.")
3687+ raise AssertionError("Performed more times than expected.")
3688+
3689+
3690+class ImplicitRunCounter(RunCounter):
3691+ """RunCounter inserted by default on any event.
3692+
3693+ This is a way to differentiate explicitly added counters and
3694+ implicit ones.
3695+ """
3696+
3697+def run_counter_recorder(mocker, event):
3698+ """Any event may be repeated once, unless disabled by default."""
3699+ if event.path.root_mock.__mocker_count__:
3700+ event.add_task(ImplicitRunCounter(1))
3701+
3702+Mocker.add_recorder(run_counter_recorder)
3703+
3704+def run_counter_removal_recorder(mocker, event):
3705+ """
3706+ Events created by getattr actions which lead to other events
3707+ may be repeated any number of times. For that, we remove implicit
3708+ run counters of any getattr actions leading to the current one.
3709+ """
3710+ parent_path = event.path.parent_path
3711+ for event in mocker.get_events()[::-1]:
3712+ if (event.path is parent_path and
3713+ event.path.actions[-1].kind == "getattr"):
3714+ for task in event.get_tasks():
3715+ if type(task) is ImplicitRunCounter:
3716+ event.remove_task(task)
3717+
3718+Mocker.add_recorder(run_counter_removal_recorder)
3719+
3720+
3721+class MockReturner(Task):
3722+ """Return a mock based on the action path."""
3723+
3724+ def __init__(self, mocker):
3725+ self.mocker = mocker
3726+
3727+ def run(self, path):
3728+ return Mock(self.mocker, path)
3729+
3730+def mock_returner_recorder(mocker, event):
3731+ """Events that lead to other events must return mock objects."""
3732+ parent_path = event.path.parent_path
3733+ for event in mocker.get_events():
3734+ if event.path is parent_path:
3735+ for task in event.get_tasks():
3736+ if isinstance(task, MockReturner):
3737+ break
3738+ else:
3739+ event.add_task(MockReturner(mocker))
3740+ break
3741+
3742+Mocker.add_recorder(mock_returner_recorder)
3743+
3744+
3745+class FunctionRunner(Task):
3746+ """Task that runs a function everything it's run.
3747+
3748+ Arguments of the last action in the path are passed to the function,
3749+ and the function result is also returned.
3750+ """
3751+
3752+ def __init__(self, func):
3753+ self._func = func
3754+
3755+ def run(self, path):
3756+ action = path.actions[-1]
3757+ return self._func(*action.args, **action.kwargs)
3758+
3759+
3760+class PathExecuter(Task):
3761+ """Task that executes a path in the real object, and returns the result."""
3762+
3763+ def __init__(self, result_callback=None):
3764+ self._result_callback = result_callback
3765+
3766+ def get_result_callback(self):
3767+ return self._result_callback
3768+
3769+ def run(self, path):
3770+ result = path.execute(path.root_object)
3771+ if self._result_callback is not None:
3772+ self._result_callback(result)
3773+ return result
3774+
3775+
3776+class Orderer(Task):
3777+ """Task to establish an order relation between two events.
3778+
3779+ An orderer task will only match once all its dependencies have
3780+ been run.
3781+ """
3782+
3783+ def __init__(self, path):
3784+ self.path = path
3785+ self._run = False
3786+ self._dependencies = []
3787+
3788+ def replay(self):
3789+ self._run = False
3790+
3791+ def has_run(self):
3792+ return self._run
3793+
3794+ def may_run(self, path):
3795+ for dependency in self._dependencies:
3796+ if not dependency.has_run():
3797+ return False
3798+ return True
3799+
3800+ def run(self, path):
3801+ for dependency in self._dependencies:
3802+ if not dependency.has_run():
3803+ raise AssertionError("Should be after: %s" % dependency.path)
3804+ self._run = True
3805+
3806+ def add_dependency(self, orderer):
3807+ self._dependencies.append(orderer)
3808+
3809+ def get_dependencies(self):
3810+ return self._dependencies
3811+
3812+
3813+class SpecChecker(Task):
3814+ """Task to check if arguments of the last action conform to a real method.
3815+ """
3816+
3817+ def __init__(self, method):
3818+ self._method = method
3819+ self._unsupported = False
3820+
3821+ if method:
3822+ try:
3823+ self._args, self._varargs, self._varkwargs, self._defaults = \
3824+ inspect.getargspec(method)
3825+ except TypeError:
3826+ self._unsupported = True
3827+ else:
3828+ if self._defaults is None:
3829+ self._defaults = ()
3830+ if type(method) is type(self.run):
3831+ self._args = self._args[1:]
3832+
3833+ def get_method(self):
3834+ return self._method
3835+
3836+ def _raise(self, message):
3837+ spec = inspect.formatargspec(self._args, self._varargs,
3838+ self._varkwargs, self._defaults)
3839+ raise AssertionError("Specification is %s%s: %s" %
3840+ (self._method.__name__, spec, message))
3841+
3842+ def verify(self):
3843+ if not self._method:
3844+ raise AssertionError("Method not found in real specification")
3845+
3846+ def may_run(self, path):
3847+ try:
3848+ self.run(path)
3849+ except AssertionError:
3850+ return False
3851+ return True
3852+
3853+ def run(self, path):
3854+ if not self._method:
3855+ raise AssertionError("Method not found in real specification")
3856+ if self._unsupported:
3857+ return # Can't check it. Happens with builtin functions. :-(
3858+ action = path.actions[-1]
3859+ obtained_len = len(action.args)
3860+ obtained_kwargs = action.kwargs.copy()
3861+ nodefaults_len = len(self._args) - len(self._defaults)
3862+ for i, name in enumerate(self._args):
3863+ if i < obtained_len and name in action.kwargs:
3864+ self._raise("%r provided twice" % name)
3865+ if (i >= obtained_len and i < nodefaults_len and
3866+ name not in action.kwargs):
3867+ self._raise("%r not provided" % name)
3868+ obtained_kwargs.pop(name, None)
3869+ if obtained_len > len(self._args) and not self._varargs:
3870+ self._raise("too many args provided")
3871+ if obtained_kwargs and not self._varkwargs:
3872+ self._raise("unknown kwargs: %s" % ", ".join(obtained_kwargs))
3873+
3874+def spec_checker_recorder(mocker, event):
3875+ spec = event.path.root_mock.__mocker_spec__
3876+ if spec:
3877+ actions = event.path.actions
3878+ if len(actions) == 1:
3879+ if actions[0].kind == "call":
3880+ method = getattr(spec, "__call__", None)
3881+ event.add_task(SpecChecker(method))
3882+ elif len(actions) == 2:
3883+ if actions[0].kind == "getattr" and actions[1].kind == "call":
3884+ method = getattr(spec, actions[0].args[0], None)
3885+ event.add_task(SpecChecker(method))
3886+
3887+Mocker.add_recorder(spec_checker_recorder)
3888+
3889+
3890+class ProxyReplacer(Task):
3891+ """Task which installs and deinstalls proxy mocks.
3892+
3893+ This task will replace a real object by a mock in all dictionaries
3894+ found in the running interpreter via the garbage collecting system.
3895+ """
3896+
3897+ def __init__(self, mock):
3898+ self.mock = mock
3899+ self.__mocker_replace__ = False
3900+
3901+ def replay(self):
3902+ global_replace(self.mock.__mocker_object__, self.mock)
3903+
3904+ def restore(self):
3905+ global_replace(self.mock, self.mock.__mocker_object__)
3906+
3907+
3908+def global_replace(remove, install):
3909+ """Replace object 'remove' with object 'install' on all dictionaries."""
3910+ for referrer in gc.get_referrers(remove):
3911+ if (type(referrer) is dict and
3912+ referrer.get("__mocker_replace__", True)):
3913+ for key, value in referrer.items():
3914+ if value is remove:
3915+ referrer[key] = install
3916+
3917+
3918+class Undefined(object):
3919+
3920+ def __repr__(self):
3921+ return "Undefined"
3922+
3923+Undefined = Undefined()
3924+
3925+
3926+class Patcher(Task):
3927+
3928+ def __init__(self):
3929+ super(Patcher, self).__init__()
3930+ self._monitored = {} # {kind: {id(object): object}}
3931+ self._patched = {}
3932+
3933+ def is_monitoring(self, obj, kind):
3934+ monitored = self._monitored.get(kind)
3935+ if monitored:
3936+ if id(obj) in monitored:
3937+ return True
3938+ cls = type(obj)
3939+ if issubclass(cls, type):
3940+ cls = obj
3941+ bases = set([id(base) for base in cls.__mro__])
3942+ bases.intersection_update(monitored)
3943+ return bool(bases)
3944+ return False
3945+
3946+ def monitor(self, obj, kind):
3947+ if kind not in self._monitored:
3948+ self._monitored[kind] = {}
3949+ self._monitored[kind][id(obj)] = obj
3950+
3951+ def patch_attr(self, obj, attr, value):
3952+ original = obj.__dict__.get(attr, Undefined)
3953+ self._patched[id(obj), attr] = obj, attr, original
3954+ setattr(obj, attr, value)
3955+
3956+ def get_unpatched_attr(self, obj, attr):
3957+ cls = type(obj)
3958+ if issubclass(cls, type):
3959+ cls = obj
3960+ result = Undefined
3961+ for mro_cls in cls.__mro__:
3962+ key = (id(mro_cls), attr)
3963+ if key in self._patched:
3964+ result = self._patched[key][2]
3965+ if result is not Undefined:
3966+ break
3967+ elif attr in mro_cls.__dict__:
3968+ result = mro_cls.__dict__.get(attr, Undefined)
3969+ break
3970+ if isinstance(result, object) and hasattr(type(result), "__get__"):
3971+ if cls is obj:
3972+ obj = None
3973+ return result.__get__(obj, cls)
3974+ return result
3975+
3976+ def _get_kind_attr(self, kind):
3977+ if kind == "getattr":
3978+ return "__getattribute__"
3979+ return "__%s__" % kind
3980+
3981+ def replay(self):
3982+ for kind in self._monitored:
3983+ attr = self._get_kind_attr(kind)
3984+ seen = set()
3985+ for obj in self._monitored[kind].itervalues():
3986+ cls = type(obj)
3987+ if issubclass(cls, type):
3988+ cls = obj
3989+ if cls not in seen:
3990+ seen.add(cls)
3991+ unpatched = getattr(cls, attr, Undefined)
3992+ self.patch_attr(cls, attr,
3993+ PatchedMethod(kind, unpatched,
3994+ self.is_monitoring))
3995+ self.patch_attr(cls, "__mocker_execute__",
3996+ self.execute)
3997+
3998+ def restore(self):
3999+ for obj, attr, original in self._patched.itervalues():
4000+ if original is Undefined:
4001+ delattr(obj, attr)
4002+ else:
4003+ setattr(obj, attr, original)
4004+ self._patched.clear()
4005+
4006+ def execute(self, action, object):
4007+ attr = self._get_kind_attr(action.kind)
4008+ unpatched = self.get_unpatched_attr(object, attr)
4009+ try:
4010+ return unpatched(*action.args, **action.kwargs)
4011+ except AttributeError:
4012+ if action.kind == "getattr":
4013+ # The normal behavior of Python is to try __getattribute__,
4014+ # and if it raises AttributeError, try __getattr__. We've
4015+ # tried the unpatched __getattribute__ above, and we'll now
4016+ # try __getattr__.
4017+ try:
4018+ __getattr__ = unpatched("__getattr__")
4019+ except AttributeError:
4020+ pass
4021+ else:
4022+ return __getattr__(*action.args, **action.kwargs)
4023+ raise
4024+
4025+
4026+class PatchedMethod(object):
4027+
4028+ def __init__(self, kind, unpatched, is_monitoring):
4029+ self._kind = kind
4030+ self._unpatched = unpatched
4031+ self._is_monitoring = is_monitoring
4032+
4033+ def __get__(self, obj, cls=None):
4034+ object = obj or cls
4035+ if not self._is_monitoring(object, self._kind):
4036+ return self._unpatched.__get__(obj, cls)
4037+ def method(*args, **kwargs):
4038+ if self._kind == "getattr" and args[0].startswith("__mocker_"):
4039+ return self._unpatched.__get__(obj, cls)(args[0])
4040+ mock = object.__mocker_mock__
4041+ return mock.__mocker_act__(self._kind, args, kwargs, object)
4042+ return method
4043+
4044+ def __call__(self, obj, *args, **kwargs):
4045+ # At least with __getattribute__, Python seems to use *both* the
4046+ # descriptor API and also call the class attribute directly. It
4047+ # looks like an interpreter bug, or at least an undocumented
4048+ # inconsistency.
4049+ return self.__get__(obj)(*args, **kwargs)
4050+
4051+
4052+def patcher_recorder(mocker, event):
4053+ mock = event.path.root_mock
4054+ if mock.__mocker_patcher__ and len(event.path.actions) == 1:
4055+ patcher = mock.__mocker_patcher__
4056+ patcher.monitor(mock.__mocker_object__, event.path.actions[0].kind)
4057+
4058+Mocker.add_recorder(patcher_recorder)
4059
4060=== added directory 'data'
4061=== added file 'data/couchdb.tmpl'
4062--- data/couchdb.tmpl 1970-01-01 00:00:00 +0000
4063+++ data/couchdb.tmpl 2009-08-20 12:55:54 +0000
4064@@ -0,0 +1,38 @@
4065+<!doctype html>
4066+<html>
4067+<head>
4068+<title>Your Desktop CouchDB</title>
4069+<script>
4070+window.onload = function() {
4071+ if (document.cookie == "yes") {
4072+ location.href = document.getElementById("there").href;
4073+ }
4074+ document.getElementById("there").addEventListener("click", function(e) {
4075+ document.cookie = "yes; expires=Thu, 31 Dec 2099 21:00:00 UTC";
4076+ }, false);
4077+ var count = 30;
4078+ setInterval(function() {
4079+ count -= 1;
4080+ if (count < 0) {
4081+ location.href = document.getElementById("there").href;
4082+ return;
4083+ }
4084+ document.getElementsByTagName("span")[0].innerHTML = count;
4085+ }, 1000);
4086+}
4087+</script>
4088+</head>
4089+<body>
4090+<h1>Desktop CouchDB</h1>
4091+<p>Your desktop CouchDB is the data store for many of your applications.
4092+You can browse around it to see which data your applications are storing.</p>
4093+<p>You should bookmark this page (by going to <strong>Bookmarks > Bookmark
4094+This Page</strong> or pressing <strong>Ctrl-D</strong>) so you can easily
4095+come back to browse your CouchDB again.</p>
4096+<p>Don't bookmark the CouchDB page itself, because its location may change!</p>
4097+<p>Taking you to your Desktop CouchDB in <span>30</span> seconds...
4098+<a id="there" href="http://[[COUCHDB_USERNAME]]:[[COUCHDB_PASSWORD]]@localhost:[[COUCHDB_PORT]]/_utils">take me
4099+there straight away from now on</a> (remember to bookmark this page first!)</p>
4100+</body>
4101+</html>
4102+
4103
4104=== added directory 'debian'
4105=== added file 'debian/changelog'
4106--- debian/changelog 1970-01-01 00:00:00 +0000
4107+++ debian/changelog 2009-09-14 23:33:14 +0000
4108@@ -0,0 +1,102 @@
4109+desktopcouch (0.4-0ubuntu1) karmic; urgency=low
4110+
4111+ * Packaging: desktopcouch-tools installed by default in Karmic (LP: #427421)
4112+ * Forcing desktopcouch auth on. (LP: #427446)
4113+ * Requiring new version of couchdb that supports authentication properly.
4114+ * Pairing updates couchdb replication system. (LP: #397663)
4115+ * Added pairing of desktop Couches to desktopcouch-tools (LP: #404087)
4116+ * Admin users in the system couchdb are no longer inherited by desktopcouch
4117+ couchdbs (LP: #424330)
4118+ * Fixed failing tests in desktopcouch (LP: #405612)
4119+ * Creating login details on initial desktopcouch setup (LP: #416413)
4120+ * Starting replication to paired servers on desktopcouch startup.
4121+ (LP: #416581)
4122+ * Unpaired couchdb peers are reconciled with replication. (LP: #424386)
4123+ * At pairing time, changing couchdb pairing address to public. (LP: #419969)
4124+ * In replication daemon, verifying local couchdb bind address is not 127/8 .
4125+ (LP: #419973)
4126+ * getPort no longer suceeds when desktopcouch isn't running. (LP: #422127)
4127+
4128+ -- Chad Miller <chad.miller@canonical.com> Mon, 14 Sep 2009 19:24:08 -0400
4129+
4130+desktopcouch (0.3.1-0ubuntu1) karmic; urgency=low
4131+
4132+ [Ken VanDine]
4133+ * debian/control
4134+ - Added depends on python-desktopcouch-records. (LP: #422179)
4135+ [Chad Miller]
4136+ * New upstream release.
4137+ * Changed Vcs-Bzr links in control file.
4138+ * Changed version dependency on couchdb.
4139+ * Converting to a full-blown source-package branch.
4140+ * Fix getPort failure. (LP: #420911, LP: #422127)
4141+ * Check couchdb bind-port in replicator. (LP: #419973)
4142+ * Change couchdb bind-port in pairing tool. (LP: #419969)
4143+
4144+ -- Chad Miller <chad.miller@canonical.com> Tue, 01 Sep 2009 11:57:25 -0400
4145+
4146+desktopcouch (0.3-0ubuntu1) karmic; urgency=low
4147+
4148+ [ Ken VanDine ]
4149+ * New upstream release (LP: #416591)
4150+ - added unit tests for couchwidget, and then fixed bug #412266
4151+ - Change to freedesktop URL for record type spec.
4152+ - First version of the contacts picker, based on CouchWidget
4153+ - Adding the desktopcouch.contacts module.
4154+ - Use subprocess.Popen and ourselves to the wait()ing,
4155+ since subprocess.call() is buggy. There's still an EINTR bug
4156+ in subprocess, though.
4157+ - Occasionally stop couchdb in tests, so we exercise the automatic
4158+ starting code. This will lead to spurious errors because of the
4159+ aforementioned subprocess bug, but it's the right thing to do.
4160+ - Abstract away some of the linuxisms and complain if we're run on
4161+ an unsupported OS.
4162+ - Fix a race condition in the process-testing code.
4163+ - Replace the TestCase module with one that doesn't complain of dirty
4164+ twisted reactors.
4165+ - Add a means of stopping the desktop couchdb daemon.
4166+ - Add an additional check that a found PID and process named correctly
4167+ is indeed a process that this user started, so we don't try to talk
4168+ to other local users' desktop couchdbs.
4169+ - Get the port at function-call time, instead of storing a port at
4170+ start-time and giving that back. The info can be stale, the old
4171+ way.
4172+ - Don't create a view per record-type; instead, call the standard
4173+ return-all-records-keyed-by-record-type and use slice notation on
4174+ the viewresults to only get back the records with that type,
4175+ which does the same thing but more elegantly.
4176+ - Remove the unused/invalid "utils" import from test_server
4177+ - Change the name of a function tested to be what actually exists in
4178+ the code.
4179+ - Refactored server.py by renaming server.get_records_and_type to
4180+ server.get_records. Also modified the function to take a record
4181+ type param if desired to only create records of that type and
4182+ optionally create a view name "get_"+ record_type. (LP: #411475)
4183+ * debian/control
4184+ - Make python-desktopcouch depend on python-gtk2 and python-gnomekeyring
4185+ - Make python-desktopcouch-records depend on python-gtk2,
4186+ python-gnomekeyring, and python-oauth.
4187+ - Remove depends for python-distutils-extra
4188+ - Fixed Vcs-Browser tag
4189+
4190+ [Elliot Murphy]
4191+ * debian/control: added build-dep on python-setuptools
4192+
4193+
4194+ [ Martin Pitt ]
4195+ * debian/control: Fix Vcs-* links.
4196+
4197+ -- Ken VanDine <ken.vandine@canonical.com> Thu, 27 Aug 2009 15:32:11 +0200
4198+
4199+desktopcouch (0.2-0ubuntu1) karmic; urgency=low
4200+
4201+ * New upstream release
4202+ * Handle the case where the pid file is empty or doesn't exist (LP: #408796)
4203+
4204+ -- Ken VanDine <ken.vandine@canonical.com> Wed, 05 Aug 2009 02:17:47 +0100
4205+
4206+desktopcouch (0.1-0ubuntu1) karmic; urgency=low
4207+
4208+ * Initial release (LP: #397662)
4209+
4210+ -- Ken VanDine <ken.vandine@canonical.com> Fri, 31 Jul 2009 13:44:45 -0400
4211
4212=== added file 'debian/compat'
4213--- debian/compat 1970-01-01 00:00:00 +0000
4214+++ debian/compat 2009-09-01 15:46:56 +0000
4215@@ -0,0 +1,1 @@
4216+6
4217
4218=== added file 'debian/control'
4219--- debian/control 1970-01-01 00:00:00 +0000
4220+++ debian/control 2009-09-14 23:33:14 +0000
4221@@ -0,0 +1,76 @@
4222+Source: desktopcouch
4223+Section: python
4224+Priority: optional
4225+Build-Depends: cdbs (>= 0.4.43),
4226+ debhelper (>= 6),
4227+ python,
4228+ python-central (>= 0.6.11),
4229+ python-distutils-extra (>= 2.8),
4230+ python-setuptools
4231+Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
4232+Standards-Version: 3.8.2
4233+XS-Python-Version: current
4234+Homepage: http://launchpad.net/desktopcouch
4235+Vcs-Bzr: https://code.launchpad.net/~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb
4236+Vcs-Browser: http://bazaar.launchpad.net/~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb
4237+
4238+Package: desktopcouch
4239+Architecture: all
4240+XB-Python-Version: ${python:Versions}
4241+Depends: ${misc:Depends},
4242+ ${python:Depends},
4243+ couchdb (>= 0.10.0~svn8138),
4244+ python-dbus,
4245+ python-couchdb (>= 0.6),
4246+ python-twisted-core,
4247+ python-gobject,
4248+ python-avahi,
4249+ python-desktopcouch,
4250+ python-desktopcouch-records,
4251+ python-gtk2
4252+Description: Desktop CouchDB instance, specific to each user
4253+ Couchdb owned by regular users in their sessions, for management of personal
4254+ data.
4255+
4256+Package: desktopcouch-tools
4257+Architecture: all
4258+XB-Python-Version: ${python:Versions}
4259+Depends: ${misc:Depends},
4260+ ${python:Depends},
4261+ python-dbus,
4262+ python-twisted-core,
4263+ python-gobject,
4264+ python-avahi,
4265+ python-desktopcouch,
4266+ python-gtk2
4267+Description: Desktop CouchDB tools
4268+ Tools used to work with DesktopCouch database.
4269+
4270+Package: python-desktopcouch
4271+Architecture: all
4272+XB-Python-Version: ${python:Versions}
4273+Depends: ${misc:Depends},
4274+ ${python:Depends},
4275+ desktopcouch,
4276+ python-dbus,
4277+ python-couchdb,
4278+ python-xdg,
4279+ python-twisted-core,
4280+ python-gtk2,
4281+ python-gnomekeyring
4282+Description: Python Desktop CouchDB
4283+ A Python library for Desktop CouchDB.
4284+
4285+Package: python-desktopcouch-records
4286+Architecture: all
4287+XB-Python-Version: ${python:Versions}
4288+Depends: ${misc:Depends},
4289+ ${python:Depends},
4290+ python-dbus,
4291+ python-couchdb,
4292+ python-desktopcouch,
4293+ python-gtk2,
4294+ python-gnomekeyring,
4295+ python-oauth
4296+Description: Desktop CouchDB Records API
4297+ A Python library for the Desktop CouchDB Records API.
4298
4299=== added file 'debian/copyright'
4300--- debian/copyright 1970-01-01 00:00:00 +0000
4301+++ debian/copyright 2009-09-01 15:46:56 +0000
4302@@ -0,0 +1,11 @@
4303+Format-Specification: http://wiki.debian.org/Proposals/CopyrightFormat
4304+Upstream-Name: desktopcouch
4305+Upstream-Maintainer: Stuart Langridge <stuart.langridge@canonical.com>
4306+Upstream-Source: https://launchpad.net/desktopcouch
4307+
4308+Files: *
4309+Copyright: (C) 2009 Canonical Ltd.
4310+
4311+License: LGPL-3
4312+ The full text of the LGPL is distributed in
4313+ /usr/share/common-licenses/LGPL-3 on Debian systems.
4314
4315=== added file 'debian/desktopcouch-tools.install'
4316--- debian/desktopcouch-tools.install 1970-01-01 00:00:00 +0000
4317+++ debian/desktopcouch-tools.install 2009-09-01 15:46:56 +0000
4318@@ -0,0 +1,4 @@
4319+debian/tmp/usr/share/applications/desktopcouch-pair.desktop
4320+debian/tmp/usr/bin/desktopcouch-pair
4321+debian/tmp/usr/share/man/man1/desktopcouch-pair.1
4322+#debian/tmp/usr/share/locale/*/LC_MESSAGES/desktopcouch.mo
4323
4324=== added file 'debian/desktopcouch.install'
4325--- debian/desktopcouch.install 1970-01-01 00:00:00 +0000
4326+++ debian/desktopcouch.install 2009-09-01 15:46:56 +0000
4327@@ -0,0 +1,3 @@
4328+debian/tmp/usr/share/desktopcouch
4329+debian/tmp/usr/lib/desktopcouch/desktopcouch-{stop,service}
4330+debian/tmp/usr/share/dbus-1/services/org.desktopcouch.CouchDB.service
4331
4332=== added file 'debian/pycompat'
4333--- debian/pycompat 1970-01-01 00:00:00 +0000
4334+++ debian/pycompat 2009-09-01 15:46:56 +0000
4335@@ -0,0 +1,1 @@
4336+2
4337
4338=== added file 'debian/python-desktopcouch-records.install'
4339--- debian/python-desktopcouch-records.install 1970-01-01 00:00:00 +0000
4340+++ debian/python-desktopcouch-records.install 2009-09-01 15:46:56 +0000
4341@@ -0,0 +1,2 @@
4342+debian/tmp/usr/share/doc/python-desktopcouch-records/api
4343+debian/tmp/usr/lib/*/*/desktopcouch/records/*
4344
4345=== added file 'debian/python-desktopcouch.install'
4346--- debian/python-desktopcouch.install 1970-01-01 00:00:00 +0000
4347+++ debian/python-desktopcouch.install 2009-09-15 05:02:20 +0000
4348@@ -0,0 +1,3 @@
4349+debian/tmp/usr/lib/*/*/desktopcouch/*.py
4350+debian/tmp/usr/lib/*/*/desktopcouch/replication_services/*.py
4351+debian/tmp/usr/lib/*/*/desktopcouch/pair/{couchdb_pairing,__init__.py}
4352
4353=== added file 'debian/rules'
4354--- debian/rules 1970-01-01 00:00:00 +0000
4355+++ debian/rules 2009-09-01 15:46:56 +0000
4356@@ -0,0 +1,7 @@
4357+#!/usr/bin/make -f
4358+
4359+DEB_PYTHON_SYSTEM := pycentral
4360+
4361+include /usr/share/cdbs/1/rules/debhelper.mk
4362+include /usr/share/cdbs/1/class/python-distutils.mk
4363+include /usr/share/cdbs/1/rules/langpack.mk
4364
4365=== added file 'debian/watch'
4366--- debian/watch 1970-01-01 00:00:00 +0000
4367+++ debian/watch 2009-09-01 15:46:56 +0000
4368@@ -0,0 +1,2 @@
4369+version=3
4370+http://launchpad.net/desktopcouch/+download .*/desktopcouch-([0-9.]+)\.tar\.gz
4371
4372=== added directory 'desktopcouch'
4373=== added file 'desktopcouch-pair.desktop.in'
4374--- desktopcouch-pair.desktop.in 1970-01-01 00:00:00 +0000
4375+++ desktopcouch-pair.desktop.in 2009-07-27 19:18:55 +0000
4376@@ -0,0 +1,8 @@
4377+[Desktop Entry]
4378+_Name=CouchDB Pairing Tool
4379+Type=Application
4380+_Comment=Utility for pairing Desktop CouchDB
4381+Exec=desktopcouch-pair
4382+Icon=
4383+Categories=Network;
4384+_GenericName=CouchDB Pairing Tool
4385
4386=== added file 'desktopcouch/__init__.py'
4387--- desktopcouch/__init__.py 1970-01-01 00:00:00 +0000
4388+++ desktopcouch/__init__.py 2009-09-09 23:24:53 +0000
4389@@ -0,0 +1,98 @@
4390+# Copyright 2009 Canonical Ltd.
4391+#
4392+# This file is part of desktopcouch.
4393+#
4394+# desktopcouch is free software: you can redistribute it and/or modify
4395+# it under the terms of the GNU Lesser General Public License version 3
4396+# as published by the Free Software Foundation.
4397+#
4398+# desktopcouch is distributed in the hope that it will be useful,
4399+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4400+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4401+# GNU Lesser General Public License for more details.
4402+#
4403+# You should have received a copy of the GNU Lesser General Public License
4404+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4405+"Desktop Couch helper files"
4406+
4407+from __future__ import with_statement
4408+import os, re
4409+from desktopcouch.start_local_couchdb import process_is_couchdb, read_pidfile
4410+
4411+def find_pid(start_if_not_running=True):
4412+ # Work out whether CouchDB is running by looking at its pid file
4413+ pid = read_pidfile()
4414+ if not process_is_couchdb(pid) and start_if_not_running:
4415+ # start CouchDB by running the startup script
4416+ print "Desktop CouchDB is not running; starting it.",
4417+ from desktopcouch import start_local_couchdb
4418+ pid = start_local_couchdb.start_couchdb()
4419+ # now load the design documents, because it's started
4420+ start_local_couchdb.update_design_documents()
4421+
4422+ if not process_is_couchdb(pid):
4423+ raise RuntimeError("desktop-couch not started")
4424+
4425+ return pid
4426+
4427+def find_port__linux(pid=None):
4428+ if pid is None:
4429+ pid = find_pid()
4430+
4431+ proc_dir = "/proc/%s" % (pid,)
4432+
4433+ # enumerate the process' file descriptors
4434+ fd_dir = os.path.join(proc_dir, 'fd')
4435+ try:
4436+ fd_paths = [os.readlink(os.path.join(fd_dir, fd))
4437+ for fd in os.listdir(fd_dir)]
4438+ except OSError:
4439+ raise RuntimeError("Unable to find file descriptors in /proc")
4440+
4441+ # identify socket fds
4442+ socket_matches = [re.match('socket:\\[([0-9]+)\\]', p) for p in fd_paths]
4443+ # extract their inode numbers
4444+ socket_inodes = [m.group(1) for m in socket_matches if m is not None]
4445+
4446+ # construct a subexpression which matches any one of these inodes
4447+ inode_subexp = "|".join(map(re.escape, socket_inodes))
4448+ # construct regexp to match /proc/net/tcp entries which are listening
4449+ # sockets having one of the given inode numbers
4450+ listening_regexp = re.compile(r'''
4451+ \s*\d+:\s* # sl
4452+ [0-9A-F]{8}: # local_address part 1
4453+ ([0-9A-F]{4})\s+ # local_address part 2
4454+ 00000000:0000\s+ # rem_address
4455+ 0A\s+ # st (0A = listening)
4456+ [0-9A-F]{8}: # tx_queue
4457+ [0-9A-F]{8}\s+ # rx_queue
4458+ [0-9A-F]{2}: # tr
4459+ [0-9A-F]{8}\s+ # tm->when
4460+ [0-9A-F]{8}\s* # retrnsmt
4461+ \d+\s+\d+\s+ # uid, timeout
4462+ (?:%s)\s+ # inode
4463+ ''' % (inode_subexp,), re.VERBOSE)
4464+
4465+ # extract the TCP port from the first matching line in /proc/$pid/net/tcp
4466+ port = None
4467+ with open(os.path.join(proc_dir, 'net', 'tcp')) as tcp_file:
4468+ for line in tcp_file:
4469+ match = listening_regexp.match(line)
4470+ if match is not None:
4471+ port = str(int(match.group(1), 16))
4472+ break
4473+ if port is None:
4474+ raise RuntimeError("Unable to find listening port")
4475+
4476+ return port
4477+
4478+
4479+
4480+import platform
4481+os_name = platform.system()
4482+try:
4483+ find_port = {
4484+ "Linux": find_port__linux
4485+ } [os_name]
4486+except KeyError:
4487+ raise NotImplementedError("os %r is not yet supported" % (os_name,))
4488
4489=== added directory 'desktopcouch/contacts'
4490=== added file 'desktopcouch/contacts/__init__.py'
4491--- desktopcouch/contacts/__init__.py 1970-01-01 00:00:00 +0000
4492+++ desktopcouch/contacts/__init__.py 2009-08-17 21:39:48 +0000
4493@@ -0,0 +1,20 @@
4494+# Copyright 2009 Canonical Ltd.
4495+#
4496+# This file is part of desktopcouch-contacts.
4497+#
4498+# desktopcouch is free software: you can redistribute it and/or modify
4499+# it under the terms of the GNU Lesser General Public License version 3
4500+# as published by the Free Software Foundation.
4501+#
4502+# desktopcouch is distributed in the hope that it will be useful,
4503+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4504+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4505+# GNU Lesser General Public License for more details.
4506+#
4507+# You should have received a copy of the GNU Lesser General Public License
4508+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4509+#
4510+# Authors: Eric Casteleijn <eric.casteleijn@canonical.com>
4511+# Nicola Larosa <nicola.larosa@canonical.com>
4512+
4513+"""UbuntuOne Contacts API"""
4514
4515=== added file 'desktopcouch/contacts/contactspicker.py'
4516--- desktopcouch/contacts/contactspicker.py 1970-01-01 00:00:00 +0000
4517+++ desktopcouch/contacts/contactspicker.py 2009-08-24 20:35:25 +0000
4518@@ -0,0 +1,81 @@
4519+# Copyright 2009 Canonical Ltd.
4520+#
4521+# This file is part of desktopcouch-contacts.
4522+#
4523+# desktopcouch is free software: you can redistribute it and/or modify
4524+# it under the terms of the GNU Lesser General Public License version 3
4525+# as published by the Free Software Foundation.
4526+#
4527+# desktopcouch is distributed in the hope that it will be useful,
4528+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4529+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4530+# GNU Lesser General Public License for more details.
4531+#
4532+# You should have received a copy of the GNU Lesser General Public License
4533+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4534+#
4535+# Authors: Rodrigo Moya <rodrigo.moya@canonical.com
4536+
4537+"""A widget to allow users to pick contacts"""
4538+
4539+import gtk
4540+from desktopcouch.contacts.record import CONTACT_RECORD_TYPE
4541+from desktopcouch.records.couchgrid import CouchGrid
4542+
4543+
4544+class ContactsPicker(gtk.VBox):
4545+ """A contacts picker"""
4546+
4547+ def __init__(self, uri=None):
4548+ """Create a new ContactsPicker widget."""
4549+
4550+ gtk.VBox.__init__(self)
4551+
4552+ # Create search entry and button
4553+ hbox = gtk.HBox()
4554+ self.pack_start(hbox, False, False, 3)
4555+
4556+ self.search_entry = gtk.Entry()
4557+ hbox.pack_start(self.search_entry, True, True, 3)
4558+
4559+ self.search_button = gtk.Button(
4560+ stock=gtk.STOCK_FIND, use_underline=True)
4561+ hbox.pack_start(self.search_button, False, False, 3)
4562+
4563+ # Create CouchGrid to contain list of contacts
4564+ self.contacts_list = CouchGrid('contacts', uri=uri)
4565+ self.contacts_list.editable = False
4566+ self.contacts_list.keys = [ "first_name", "last_name" ]
4567+ self.contacts_list.record_type = CONTACT_RECORD_TYPE
4568+
4569+ #Pimp out the columns with some nicer titles
4570+ #TODO: this should be set up for translatability
4571+ columns = self.contacts_list.get_columns()
4572+ columns[0].set_title("First Name")
4573+ columns[1].set_title("Last Name")
4574+
4575+ self.contacts_list.show()
4576+ self.pack_start(self.contacts_list, True, True, 3)
4577+
4578+ def get_contacts_list(self):
4579+ """get_contacts_list - gtk.Widget value
4580+ Gets the CouchGrid inside the ContactsPicker widget
4581+ """
4582+ return self.contacts_list
4583+
4584+if __name__ == "__main__":
4585+ """creates a test ContactsPicker if called directly"""
4586+
4587+ # Create and show a test window
4588+ win = gtk.Dialog("ContactsPicker widget test", None, 0,
4589+ (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))
4590+ win.connect("response", gtk.main_quit)
4591+ win.resize(300, 450)
4592+
4593+ # Create the contacts picker widget
4594+ picker = ContactsPicker()
4595+ win.get_content_area().pack_start(picker, True, True, 3)
4596+
4597+ # Run the test application
4598+ win.show_all()
4599+ gtk.main()
4600
4601=== added file 'desktopcouch/contacts/record.py'
4602--- desktopcouch/contacts/record.py 1970-01-01 00:00:00 +0000
4603+++ desktopcouch/contacts/record.py 2009-08-19 10:07:54 +0000
4604@@ -0,0 +1,34 @@
4605+# Copyright 2009 Canonical Ltd.
4606+#
4607+# This file is part of desktopcouch-contacts.
4608+#
4609+# desktopcouch is free software: you can redistribute it and/or modify
4610+# it under the terms of the GNU Lesser General Public License version 3
4611+# as published by the Free Software Foundation.
4612+#
4613+# desktopcouch is distributed in the hope that it will be useful,
4614+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4615+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4616+# GNU Lesser General Public License for more details.
4617+#
4618+# You should have received a copy of the GNU Lesser General Public License
4619+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4620+#
4621+# Authors: Eric Casteleijn <eric.casteleijn@canonical.com>
4622+# Nicola Larosa <nicola.larosa@canonical.com>
4623+# Mark G. Saye <mark.saye@canonical.com>
4624+
4625+
4626+"""A dictionary based contact record representation."""
4627+
4628+from desktopcouch.records.record import Record
4629+
4630+CONTACT_RECORD_TYPE = 'http://www.freedesktop.org/wiki/Specifications/desktopcouch/contact'
4631+
4632+
4633+class Contact(Record):
4634+ """An Ubuntuone Contact Record."""
4635+
4636+ def __init__(self, data=None, record_id=None):
4637+ super(Contact, self).__init__(
4638+ record_id=record_id, data=data, record_type=CONTACT_RECORD_TYPE)
4639
4640=== added file 'desktopcouch/contacts/schema.txt'
4641--- desktopcouch/contacts/schema.txt 1970-01-01 00:00:00 +0000
4642+++ desktopcouch/contacts/schema.txt 2009-08-19 10:07:54 +0000
4643@@ -0,0 +1,50 @@
4644+# Copyright 2009 Canonical Ltd.
4645+#
4646+# This file is part of desktopcouch-contacts.
4647+#
4648+# desktopcouch is free software: you can redistribute it and/or modify
4649+# it under the terms of the GNU Lesser General Public License version 3
4650+# as published by the Free Software Foundation.
4651+#
4652+# desktopcouch is distributed in the hope that it will be useful,
4653+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4654+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4655+# GNU Lesser General Public License for more details.
4656+#
4657+# You should have received a copy of the GNU Lesser General Public License
4658+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4659+
4660+Schema
4661+
4662+The proposed CouchDB contact schema is as follows:
4663+
4664+Core fields
4665+
4666+ * record_type 'http://www.freedesktop.org/wiki/Specifications/desktopcouch/contact'
4667+ * first_name (string)
4668+ * last_name (string)
4669+ * birth_date (string, "YYYY-MM-DD")
4670+ * addresses (MergeableList of "address" dictionaries)
4671+ o city (string)
4672+ o address1 (string)
4673+ o address2 (string)
4674+ o pobox (string)
4675+ o state (string)
4676+ o country (string)
4677+ o postalcode (string)
4678+ o description (string, e.g., "Home")
4679+ * email_addresses (MergeableList of "emailaddress" dictionaries)
4680+ o address (string),
4681+ o description (string)
4682+ * phone_numbers (MergeableList of "phone number" dictionaries)
4683+ o number (string)
4684+ o description (string)
4685+ * application_annotations Everything else, organized per application.
4686+
4687+Note: None of the core fields are mandatory, but applications should
4688+not add any other fields at the top level of the record. Any fields
4689+needed not defined here should be put under application_annotations in
4690+the namespace of the application there. So for Ubuntu One:
4691+
4692+ "application_annotations": {
4693+ "Ubuntu One": {<Ubuntu One specific fields here>}}
4694
4695=== added directory 'desktopcouch/contacts/testing'
4696=== added file 'desktopcouch/contacts/testing/__init__.py'
4697--- desktopcouch/contacts/testing/__init__.py 1970-01-01 00:00:00 +0000
4698+++ desktopcouch/contacts/testing/__init__.py 2009-08-17 21:39:48 +0000
4699@@ -0,0 +1,20 @@
4700+# Copyright 2009 Canonical Ltd.
4701+#
4702+# This file is part of desktopcouch-contacts.
4703+#
4704+# desktopcouch is free software: you can redistribute it and/or modify
4705+# it under the terms of the GNU Lesser General Public License version 3
4706+# as published by the Free Software Foundation.
4707+#
4708+# desktopcouch is distributed in the hope that it will be useful,
4709+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4710+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4711+# GNU Lesser General Public License for more details.
4712+#
4713+# You should have received a copy of the GNU Lesser General Public License
4714+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4715+#
4716+# Authors: Stuart Langridge <stuart.langridge@canonical.com>
4717+# Nicola Larosa <nicola.larosa@canonical.com>
4718+
4719+"""Support code for tests"""
4720
4721=== added file 'desktopcouch/contacts/testing/create.py'
4722--- desktopcouch/contacts/testing/create.py 1970-01-01 00:00:00 +0000
4723+++ desktopcouch/contacts/testing/create.py 2009-09-09 23:24:53 +0000
4724@@ -0,0 +1,178 @@
4725+# Copyright 2009 Canonical Ltd.
4726+#
4727+# This file is part of desktopcouch-contacts.
4728+#
4729+# desktopcouch is free software: you can redistribute it and/or modify
4730+# it under the terms of the GNU Lesser General Public License version 3
4731+# as published by the Free Software Foundation.
4732+#
4733+# desktopcouch is distributed in the hope that it will be useful,
4734+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4735+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4736+# GNU Lesser General Public License for more details.
4737+#
4738+# You should have received a copy of the GNU Lesser General Public License
4739+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4740+#
4741+# Authors: Stuart Langridge <stuart.langridge@canonical.com>
4742+# Nicola Larosa <nicola.larosa@canonical.com>
4743+
4744+"""Creating CouchDb-stored contacts for testing"""
4745+
4746+import random, string, uuid
4747+
4748+from couchdb import Server
4749+import desktopcouch
4750+
4751+CONTACT_DOCTYPE = 'http://www.freedesktop.org/wiki/Specifications/desktopcouch/contact'
4752+COUCHDB_SYS_PORT = 5984
4753+
4754+FIRST_NAMES = ('Jack', 'Thomas', 'Oliver', 'Joshua', 'Harry', 'Charlie',
4755+ 'Daniel', 'William', 'James', 'Alfie', 'Grace', 'Ruby', 'Olivia',
4756+ 'Emily', 'Jessica', 'Sophie', 'Chloe', 'Lily', 'Ella', 'Amelia')
4757+LAST_NAMES = ('Dalglish', 'Grobbelaar', 'Lawrenson', 'Beglin', 'Nicol',
4758+ 'Whelan', 'Hansen', 'Johnston', 'Rush', 'Molby', 'MacDonald', 'McMahon',
4759+ 'Penny', 'Leicester', 'Langley', 'Commodore', 'Touchstone', 'Fielding')
4760+COMPANIES = ('Gostram', 'Grulthing', 'Nasform', 'Smarfish', 'Builsank')
4761+STREET_TYPES = ('Street', 'Road', 'Lane', 'Avenue', 'Square', 'Park', 'Mall')
4762+CITIES = ('Scunthorpe', 'Birmingham', 'Cambridge', 'Durham', 'Bedford')
4763+COUNTRIES = ('England', 'Ireland', 'Scotland', 'Wales')
4764+
4765+def head_or_tails():
4766+ """Randomly return True or False"""
4767+ return random.choice((False, True))
4768+
4769+def random_bools(num_bools, at_least_one_true=True):
4770+ """
4771+ Return a sequence of random booleans. If at_least_one_true,
4772+ guarantee at list one True value.
4773+ """
4774+ if num_bools < 2:
4775+ raise RuntimeError('Cannot build a sequence smaller than two elements')
4776+ bools = [head_or_tails() for __ in range(num_bools)]
4777+ if at_least_one_true and not any(bools):
4778+ bools[random.randrange(num_bools)] = True
4779+ return bools
4780+
4781+def random_string(length=10, upper=False):
4782+ """
4783+ Return a string, of specified length, of random lower or uppercase letters.
4784+ """
4785+ charset = string.uppercase if upper else string.lowercase
4786+ return ''.join(random.sample(charset, length))
4787+
4788+def random_postal_address():
4789+ """Return something that looks like a postal address"""
4790+ return '%d %s %s' % (random.randint(1, 100), random.choice(LAST_NAMES),
4791+ random.choice(STREET_TYPES))
4792+
4793+def random_email_address(
4794+ first_name='', last_name='', company='', address_type='other'):
4795+ """
4796+ Return something that looks like an email address.
4797+ address_type values: 'personal', 'work', 'other'.
4798+ """
4799+ # avoid including the dot if one or both names are missing
4800+ pers_name = '.'.join([name for name in (first_name, last_name) if name])
4801+ return {'personal': pers_name, 'work': company,
4802+ }.get(address_type, random_string(5)) + '@example.com'
4803+
4804+def random_postal_code():
4805+ """Return something that looks like a postal code"""
4806+ return '%s12 3%s' % (random_string(2, True), random_string(2, True))
4807+
4808+def random_phone_number():
4809+ """Return something that looks like a phone number"""
4810+ return '+%s %s %s %s' % (random.randint(10, 99), random.randint(10, 99),
4811+ random.randint(1000, 9999), random.randint(1000, 9999))
4812+
4813+def random_birth_date():
4814+ """Return something that looks like a birth date"""
4815+ return '%04d-%02d-%02d' % (random.randint(1900, 2006),
4816+ random.randint(1, 12), random.randint(1, 28))
4817+
4818+def make_one_contact(maincount, doctype, app_annots):
4819+ """Make up one contact randomly"""
4820+ # Record schema
4821+ fielddict = {'record_type': doctype, 'record_type_version': '1.0'}
4822+ # Names
4823+ # at least one of the three will be present
4824+ has_first_name, has_last_name, has_company_name = random_bools(3)
4825+ first_name = (random.choice(FIRST_NAMES) + str(maincount)
4826+ ) if has_first_name else ''
4827+ last_name = random.choice(LAST_NAMES) if has_last_name else ''
4828+ company = (random.choice(COMPANIES) + str(maincount)
4829+ ) if has_company_name else ''
4830+ # Address places and types
4831+ address_places, email_types, phone_places = [], [], []
4832+ if has_first_name or has_last_name:
4833+ for (has_it, seq, val) in zip(
4834+ # at least one of the three will be present
4835+ random_bools(3),
4836+ (address_places, email_types, phone_places),
4837+ ('home', 'personal', 'home')):
4838+ if has_it:
4839+ seq.append(val)
4840+ if has_company_name:
4841+ for (has_it, seq) in zip(
4842+ # at least one of the three will be present
4843+ random_bools(3),
4844+ (address_places, email_types, phone_places)):
4845+ if has_it:
4846+ seq.append('work')
4847+ for (has_it, seq) in zip(
4848+ # none of the three may be present
4849+ random_bools(3, at_least_one_true=False),
4850+ (address_places, email_types, phone_places)):
4851+ if has_it:
4852+ seq.append('other')
4853+ # Addresses
4854+ addresses = {}
4855+ for address_type in address_places:
4856+ addresses[str(uuid.uuid4())] = {
4857+ 'address1': random_postal_address(), 'address2': '',
4858+ 'pobox': '', 'city': random.choice(CITIES),
4859+ 'state': '', 'postalcode': random_postal_code(),
4860+ 'country': random.choice(COUNTRIES), 'description': address_type}
4861+ # Email addresses
4862+ email_addresses = {}
4863+ for email_address_type in email_types:
4864+ email_addresses[str(uuid.uuid4())] = {
4865+ 'address': random_email_address(
4866+ first_name, last_name, company, email_address_type),
4867+ 'description': email_address_type}
4868+ # Phone numbers
4869+ phone_numbers = {}
4870+ for phone_number_type in phone_places:
4871+ phone_numbers[str(uuid.uuid4())] = {
4872+ 'priority': 0, 'number': random_phone_number(),
4873+ 'description': phone_number_type}
4874+ # Store data in fielddict
4875+ if (has_first_name or has_last_name) and head_or_tails():
4876+ fielddict['birth_date'] = random_birth_date()
4877+ fielddict.update({'first_name': first_name, 'last_name': last_name,
4878+ 'addresses': addresses, 'email_addresses': email_addresses,
4879+ 'phone_numbers': phone_numbers, 'company': company})
4880+ # Possibly add example application annotations
4881+ if app_annots:
4882+ fielddict['application_annotations'] = app_annots
4883+ return fielddict
4884+
4885+def create_many_contacts(
4886+ num_contacts=10, host='localhost', port=None,
4887+ db_name='contacts', doctype=CONTACT_DOCTYPE, app_annots=None):
4888+ """Make many contacts and create their records"""
4889+ if port is None:
4890+ desktopcouch.find_pid()
4891+ port = desktopcouch.find_port()
4892+ server_url = 'http://%s:%s/' % (host, port)
4893+ server = Server(server_url)
4894+ db = server[db_name] if db_name in server else server.create(db_name)
4895+ record_ids = []
4896+ for maincount in range(1, num_contacts + 1):
4897+ # Make the contact
4898+ fielddict = make_one_contact(maincount, doctype, app_annots)
4899+ # Store data in CouchDB
4900+ record_id = db.create(fielddict)
4901+ record_ids.append(record_id)
4902+ return record_ids
4903
4904=== added directory 'desktopcouch/contacts/tests'
4905=== added file 'desktopcouch/contacts/tests/__init__.py'
4906--- desktopcouch/contacts/tests/__init__.py 1970-01-01 00:00:00 +0000
4907+++ desktopcouch/contacts/tests/__init__.py 2009-09-07 09:23:36 +0000
4908@@ -0,0 +1,18 @@
4909+# Copyright 2009 Canonical Ltd.
4910+#
4911+# This file is part of desktopcouch-contacts.
4912+#
4913+# desktopcouch is free software: you can redistribute it and/or modify
4914+# it under the terms of the GNU Lesser General Public License version 3
4915+# as published by the Free Software Foundation.
4916+#
4917+# desktopcouch is distributed in the hope that it will be useful,
4918+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4919+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4920+# GNU Lesser General Public License for more details.
4921+#
4922+# You should have received a copy of the GNU Lesser General Public License
4923+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4924+
4925+"""Tests for Contacts API"""
4926+
4927
4928=== added file 'desktopcouch/contacts/tests/test_contactspicker.py'
4929--- desktopcouch/contacts/tests/test_contactspicker.py 1970-01-01 00:00:00 +0000
4930+++ desktopcouch/contacts/tests/test_contactspicker.py 2009-09-01 22:29:01 +0000
4931@@ -0,0 +1,54 @@
4932+# Copyright 2009 Canonical Ltd.
4933+#
4934+# This file is part of desktopcouch-contacts.
4935+#
4936+# desktopcouch is free software: you can redistribute it and/or modify
4937+# it under the terms of the GNU Lesser General Public License version 3
4938+# as published by the Free Software Foundation.
4939+#
4940+# desktopcouch is distributed in the hope that it will be useful,
4941+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4942+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4943+# GNU Lesser General Public License for more details.
4944+#
4945+# You should have received a copy of the GNU Lesser General Public License
4946+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4947+#
4948+# Authors: Rick Spencer <rick.spencer@canonical.com>
4949+
4950+"""Tests for the ContactsPicker class"""
4951+
4952+import testtools
4953+import gtk
4954+
4955+from desktopcouch.tests import xdg_cache
4956+
4957+from desktopcouch.contacts.contactspicker import ContactsPicker
4958+from desktopcouch.records.server import CouchDatabase
4959+
4960+class TestContactsPicker(testtools.TestCase):
4961+ """Test the Contact Picker Window."""
4962+
4963+ def setUp(self):
4964+ """setup each test"""
4965+ # Connect to CouchDB server
4966+ self.assert_(xdg_cache)
4967+ self.dbname = 'contacts'
4968+ self.database = CouchDatabase(self.dbname, create=True)
4969+
4970+ def tearDown(self):
4971+ """tear down each test"""
4972+ del self.database._server[self.dbname]
4973+
4974+ def test_can_contruct_contactspicker(self):
4975+ """Test that we can build the window"""
4976+ # Create and show a test window
4977+ win = gtk.Dialog("ContactsPicker widget test", None, 0,
4978+ (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))
4979+ win.connect("response", gtk.main_quit)
4980+ win.resize(300, 450)
4981+
4982+ # Create the contacts picker widget
4983+ picker = ContactsPicker()
4984+ win.get_content_area().pack_start(picker, True, True, 3)
4985+ self.assert_(picker.get_contacts_list())
4986
4987=== added file 'desktopcouch/contacts/tests/test_create.py'
4988--- desktopcouch/contacts/tests/test_create.py 1970-01-01 00:00:00 +0000
4989+++ desktopcouch/contacts/tests/test_create.py 2009-09-14 19:02:58 +0000
4990@@ -0,0 +1,67 @@
4991+# Copyright 2009 Canonical Ltd.
4992+#
4993+# This file is part of desktopcouch-contacts.
4994+#
4995+# desktopcouch is free software: you can redistribute it and/or modify
4996+# it under the terms of the GNU Lesser General Public License version 3
4997+# as published by the Free Software Foundation.
4998+#
4999+# desktopcouch is distributed in the hope that it will be useful,
5000+# but WITHOUT ANY WARRANTY; without even the implied warranty of
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches